Resources:
https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/
Https://stackoverflow.com/questions/35534906/java-hashmap-getobject-infinite-loop
Some implementation classes of map and their characteristics
class |
thread safe |
attribute |
Hashtable |
Yes |
key cannot be null |
HashMap |
no |
Read-write efficiency is highest, but improper use in Java6 multithreaded environments can lead to a dead loop, which in turn leads to high CPU usage (see the principle: http://coolshell.cn/articles/ 9606.html) |
collections.synchronizedmap |
is |
Collections.synchronizedmap locks on all methods of map, efficiency is equivalent to Hashtable |
Concurr Enthashmap |
Yes |
takes a segmented lock, get is generally unlocked, put fragment lock, key/value cannot be null, Efficiency second only to HashMap |
The following code tests the reading and writing efficiency of various
Importjava.util.Collections;ImportJava.util.HashMap;Importjava.util.Hashtable;ImportJava.util.Map;ImportJava.util.concurrent.ConcurrentHashMap;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.TimeUnit;/*** @Description: Test Map*/ Public classThreadmaptest { Public Static voidMain (string[] args)throwsinterruptedexception {Map<integer, integer> hashtable =NewHashtable<>(); Map<integer, integer> HashMap =NewHashmap<>(); Map<integer, integer> synchronizedhashmap = Collections.synchronizedmap (NewHashmap<>()); Map<integer, integer> concurrenthashmap =NewConcurrenthashmap<>(); Test (Hashtable); Test (HASHMAP); Test (SYNCHRONIZEDHASHMAP); Test (CONCURRENTHASHMAP); } Private Static voidTest (Map<integer, integer> Map)throwsinterruptedexception {intTesttimes = 5; LongTotaltimemillis = 0; for(intk = 0; K < Testtimes; k++) {Totaltimemillis+=costtimemillis (map); } System.out.println ("Test" + map.getclass () + "Average Time" + (Totaltimemillis/testtimes)); } Private Static LongCosttimemillis (Map<integer, integer> Map)throwsinterruptedexception {intCount = 5; Executorservice Executorservice=Executors.newfixedthreadpool (count); LongStartmillis =System.currenttimemillis (); for(inti = 0; I < count; i++) {Executorservice.execute (NewRunnable () {@Override Public voidrun () { for(intj = 0; J < 500000; J + +) {Map.put (0, 0); Map.get (0); } } }); } executorservice.shutdown (); Executorservice.awaittermination (Long.max_value, timeunit.days); returnSystem.currenttimemillis ()-Startmillis; }}
The output results are as follows:
class java.util.Hashtable Average Time 267class Java.util.HashMap average time class Java.util.collections$synchronizedmap average Time 262class Java.util.concurrent.ConcurrentHashMap Average Time 167
Java Multithreaded Series six--map implementation class