Java Reference
In-Depth Information
Concurrent Maps
Sometimes you need to perform multiple operations on a map atomically when the map is used by multiple threads
concurrently. For example, you may want to put a new key-value pair in a map only if the key does not already exist in
the map. Your code may look as follows:
Map<String,String> map = ...;
String key = ...;
String value = ...;
// Need to lock the entire map
synchronized(map) {
if (map.containsKey(key)) {
// Key is already in the map
}
else {
map.put(key, value); // Add the new key-value
}
}
In this code, you had to lock the entire map just to put a new key-value pair if the key was absent in the map.
Locking the map was necessary because you needed to perform two things atomically: testing for a key existence and
putting the key-value if the test fails. When these two operations are being performed on the map by a thread, no other
thread can lock the map for any other operations. A ConcurrentMap enables you to perform concurrent operations,
like the one I discussed, without resorting to locking the map.
You can choose the level of concurrency when you create a concurrent map using its implementation class. The
level of concurrency is specified as the estimated number of threads that would perform the write operations on the
map. The map will try to adjust those many threads concurrently. A ConcurrentMap does not lock the entire map.
Even if it locks the entire map, other threads will still be able to perform read and write operations on it because it uses
fine-grained synchronization mechanism based on a compare-and-set primitive.
The ConcurrentHashMap class is an implementation class for the ConcurrentMap interface. Both of them are in the
java.util.concurrent package.
Listing 12-33 demonstrates the use of a ConcurrentMap . The example simply shows how to create and use some
of the methods of a ConcurrentMap . Typically, you should use a ConcurrentMap in a multi-threaded environment.
The program does not use multiple threads to access the map. It only demonstrates use of some of the methods of the
ConcurrentMap interface.
Listing 12-33. Using a ConcurrentMap
// ConcurrentMapTest.java
package com.jdojo.collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class ConcurrentMapTest {
public static void main(String[] args) {
ConcurrentMap<String,String> cMap = new ConcurrentHashMap<>();
cMap.put("one", "one");
System.out.println("Concurrent Map: " + cMap);
 
Search WWH ::




Custom Search