Created
December 1, 2016 08:25
-
-
Save micw/f39fcdb48fdda47c834dbbbc7bc8d455 to your computer and use it in GitHub Desktop.
Example how to synchronize task by an indentifier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package locking; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.concurrent.atomic.AtomicInteger; | |
public class LockingTest | |
{ | |
public static void main(String[] args) | |
{ | |
new LockingTest().start(); | |
} | |
volatile long startTs; | |
public void start() | |
{ | |
List<Thread> threads=new ArrayList<>(); | |
for (int i=0;i<100;i++) | |
{ | |
final int workId=i % 2; | |
threads.add(new Thread(()->doWork(workId))); | |
} | |
startTs=System.currentTimeMillis(); | |
threads.stream().forEach((t)->t.start()); | |
} | |
protected final Map<Integer,AtomicInteger> LOCK_MAP=new HashMap<>(); | |
public void doWork(Integer workId) | |
{ | |
String id="#"+workId+" with thread "+Thread.currentThread().getName(); | |
AtomicInteger lock; | |
synchronized(LOCK_MAP) // globaler Lock | |
{ | |
lock=LOCK_MAP.get(workId); | |
if (lock==null) | |
{ | |
System.err.println("New lock for "+id+" ts: "+(System.currentTimeMillis()-startTs)); | |
lock=new AtomicInteger(1); | |
LOCK_MAP.put(workId,lock); | |
} | |
else | |
{ | |
lock.incrementAndGet(); | |
} | |
} | |
System.err.println("About to start work "+id+" ts: "+(System.currentTimeMillis()-startTs)); | |
System.err.println("Workers for this id: "+lock.get()); | |
synchronized(lock) | |
{ | |
try | |
{ | |
System.err.println("Start work "+id+" ts: "+(System.currentTimeMillis()-startTs)); | |
doActualWork(); | |
System.err.println("Done work "+id+" ts: "+(System.currentTimeMillis()-startTs)); | |
} | |
finally | |
{ | |
synchronized(LOCK_MAP) // globaler Lock | |
{ | |
if (lock.decrementAndGet()==0) | |
{ | |
System.err.println("Remove lock for "+id+" ts: "+(System.currentTimeMillis()-startTs)); | |
LOCK_MAP.remove(workId); | |
} | |
} | |
} | |
} | |
} | |
protected void doActualWork() | |
{ | |
try | |
{ | |
Thread.sleep(100); | |
} | |
catch (Exception ex) | |
{ | |
// ignored | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment