Java Reference
In-Depth Information
Random random = new Random();
private void startUpdateThread(final int i, final
ConcurrentMap<Integer, String> concurrentMap) {
Thread thread = new Thread(() -> {
int randomInt = random.nextInt(20);
String previousEntry
= concurrentMap.putIfAbsent(randomInt, "Thread # " + i
+
" has made it!");
if (previousEntry != null) {
System.out.println("Thread # " + i + " tried
to update it but guess what,
we're too late!");
} else {
System.out.println("Thread # " + i + " has
made it!");
}
});
thread.start();
}
When running the program, some of the entries will be successfully inserted, while
others will not because the key has already been inserted by another thread.
How It Works
Updating a Map concurrently is difficult because it involves two operations: a check-
then-act type of operation. First, the Map has to be checked to see whether an entry
already exists in it. If the entry doesn't exist, you can put the key and the value into the
Map . On the other hand, if the key exists, the value for the key is retrieved. To do so,
we use the ConcurrentMap 's putIfAbsent atomic operation. This ensures that
either the key was present so the value is not overwritten, or the key was not present
and so the value is set. For the JDK implementations of ConcurrentMap , the
putIfAbsent() method will return null if there was no value for the key or return
the current value if the key has a value. By asserting that the putIfAbsent() meth-
Search WWH ::




Custom Search