Original address: Http://www.concretepage.com/java/example_concurrenthashmap_java
On the This page we'll provide example of Concurrenthashmap in Java. Concurrenthashmap is the thread safe but does does use the locking on the complete map. It is fast and have better performance in comparison to Hashtable in concurrent environment. Find some methods of ConcurrentHashMap .
get () : Pass The key as an argument and it would return associated value.
put (): Pass key and value and it'll map.
putifabsent (): Pass key and value and it would map only if key was not already present.
Remove (): Removes the entry for the given key.
1.Concurrency for Retrieval: Retrieval of elements fromdoes not use locking. IT may overlap with update operation. We get the elements of last successfully completed update operation. In case of aggregate operations such asConcurrentHashMapandputAll, concurrent retrieval may show insertion or removal of the only some elements.clear()
2.Iteration of Concurrenthashmap: Iterators and enumerations also return the elements which has been concurrently added while iterating.does not throwConcurrentHashMap.ConcurrentModificationException
3.Concurrency for Updates: Concurrent updates is thread safe.Constructor has a optional concurrency level argument. The default value is 16. This is the estimated number of concurrently updating threads. It is used in internal sizing to accommodate concurrently updating threads. Hash table is internally partitioned to the concurrency level number so that it can avoid updating concurrent thread con Tention.ConcurrentHashMap
Find the example.
Concurrenthashmapdemo.java
PackageCom.Concretepage;ImportJava.Util.Iterator;ImportJava.Util.Concurrent.Concurrenthashmap;ImportJava.Util.Concurrent.Executorservice;ImportJava.Util.Concurrent.Executors;Public Class Concurrenthashmapdemo { Private Final Concurrenthashmap<Integer,String>Conhashmap= New Concurrenthashmap<Integer,String> (); Public Static voidMain(String[]Args) { ExecutorserviceService= Executors.Newfixedthreadpool(3); ConcurrenthashmapdemoOb= New Concurrenthashmapdemo();Service.Execute(Ob.New Writethreasone());Service.Execute(Ob.New Writethreastwo());Service.Execute(Ob.New Readthread());Service.Shutdownnow(); } Class Writethreasone Implements Runnable {@OverridePublic voidRun() {For(IntI= 1;I<=10;I++) {Conhashmap.Putifabsent(I, A+I);}} } Class Writethreastwo Implements Runnable {@OverridePublic voidRun() {For(IntI= 1;I<=5;I++) {Conhashmap.Put(I, B+I);}