Map

Real programmers can write assembly code in any language. Larry Wall

ConcurrentHashMap

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-22 20:36:48

0 Comments


Definition

A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates from multiple threads. Iterators are designed to be used by only one thread at a time. ConcurrentHashMap does not guarantee the runtime of its operations as part of its contract. It also allows tuning for certain load factors.

Character

Full support for accessing from concurrent threads
Do not throw ConcurrentModificationException.
Iterators can be accessed from only one thread.
Does not allow null to be used as a key or value.
When multiple threads try to retrieve and update, most recently completed update take to retrieve the data
The concurrent update based on concurrencyLevel constructor argument. If only one thread is updating and others only read, you can start concurrencyLevel with one.

source Code

								
package com.careerdrill.collections.map;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentHashMapUse {
	
	
	private static final String CONCURRENCY_LEVEL_DEFAULT = "2";
	 private static final String CONCURRENCY_KEY = "ConcurrentHashMap";
	 private ConcurrentMap< Double, Double > sqrtCache = new ConcurrentHashMap< Double, Double >();
	 
	 public double getSqrt(Double d) {
	     Double sqrt = sqrtCache.get(d);
	     if(sqrt == null) {
	         sqrt = Math.sqrt(d);
	         System.out.printf("calculated sqrt of %s = %s%n", d, sqrt);
	         Double existing = sqrtCache.putIfAbsent(d, sqrt);
	         if(existing != null) {
	             System.out.printf("Remove the calculated sqrt %s and use the cached sqrt %s", sqrt, existing);
	             sqrt = existing;
	         }
	     }
	     return sqrt;
	 }
	 
	public static void main(String[] args) {
		final ConcurrentHashMapUse test = new ConcurrentHashMapUse();
	     final int concurrencyLevel = Integer.parseInt(System.getProperty(CONCURRENCY_KEY, CONCURRENCY_LEVEL_DEFAULT));
	     final ExecutorService executor = Executors.newCachedThreadPool();
	 
	     String []strarray={ "2", "4"};
	     try {
	         for(int i = 0; i < concurrencyLevel; i++) {
	             for(String s : strarray) {
	                 final Double d = Double.valueOf(s);
	                 executor.submit(new Runnable() {
	                     @Override public void run() {
	                         System.out.printf("sqrt of %s = %s in thread %s%n",
	                             d, test.getSqrt(d), Thread.currentThread().getName());
	                     }
	                     
	                 });
	             }
	         }
	     } finally {
	         executor.shutdown();
	     }
	}

}
						

Output

    					 
Calculated sqrt of 2.0 = 1.4142135623730951
Calculated sqrt of 2.0 = 1.4142135623730951
Calculated sqrt of 4.0 = 2.0
Calculated sqrt of 4.0 = 2.0
sqrt of 4.0 = 2.0 in thread pool-1-thread-4
Remove the calculated sqrt 1.4142135623730951 and use the cached sqrt 1.4142135623730951sqrt of 2.0 = 1.4142135623730951 in thread pool-1-thread-3
sqrt of 2.0 = 1.4142135623730951 in thread pool-1-thread-1
Remove the calculated sqrt 2.0 and use the cached sqrt 2.0sqrt of 4.0 = 2.0 in thread pool-1-thread-2
    					 
					    

Comparison

ConcurrentHashMap ConcurrentSkipListMap
Does not guarantee the runtime of its operations Guarantees average O(log(n)) performance
Does not allow null to be used as a key or value Null value and null keys are not allowed
Do not maintain insertion order Elements fetched in natural order
Support Only Serializable Support cloneable and Serializable
Do not support ceilingEntry, ceilingKey, firstEntry, floorEntry operations Support ceilingEntry, ceilingKey, firstEntry, floorEntry operations

When to use

If you need to allow multiple threads using a hash map, you can use ConcurrentHashMap.

0 Comments



Please login to add comments.