Monday, July 23, 2012

Exploring Concurreny in Java


The Article contains my learning and notes about concurrency in Java

ConcurrentHashMap

Use ConcurrentHashMap if performance is critical while HashMap in a scenario multiple threads are accessing the HashMap rather than using the collection method
Collections.synchronizedMap(Map).
Here the method use to put lock on entire map object and hence update by any thread is reflected to all other thread.
Where as ConcurrentHashMap only lock the portion of data while updating the map allowing many threads to update the map and hence did not throw ConcurrentModificationException.

Synchronizing on the whole map fails to take advantage of a possible optimisation: because hash maps store their data in a series of separate buckets, it is in principle possible to lock only the portion of the map that is being accessed. This optimisation is generally called lock striping.
Java 5 brings a hash map optimised in this way in the form of ConcurrentHashMap. A combination of lock striping plus judicious use of volatile variables gives the class two highly concurrent properties:
  • Writing to a ConcurrentHashMap locks only a portion of the map;
  • Reads can generally occur without locking

Due to the concurrent nature of this collection the method that operate on entire map like size and isEmpty only return approximate value.The collection is expected to modified continuously.

Since ConcurrentHashMap can not locked for exclusive access, there are following atomic methods provided for general usage.



// Insert into map only if no value is mapped from K
V putIfAbsent(K key, V value);

// Remove only if K is mapped to V
boolean remove(K key, V value);

// Replace value only if K is mapped to oldValue
boolean replace(K key, V oldValue, V newValue);

// Replace value only if K is mapped to some value
V replace(K key, V newValue);
 
Like ConcurrentHashMap there is no such class name ConcurrentHashSet has been provided.


No comments:

Post a Comment