Thread-safe map

The thread-safe version of a Map is ConcurrentHashMap.

The following table enumerates the Java built-in single-thread and multithreaded maps:

Single thread

Multithreaded

HashMap

TreeMap (sorted keys)

LinkedHashMap (maintain insertion order)

IdentityHashMap (keys compared via ==)

WeakHashMap

EnumMap

ConcurrentHashMap

ConcurrentSkipListMap (sorted map)

Hashtable

ConcurrentHashMap allows retrieval operations (for example, get()) without blocking. This means that retrieval operations may overlap with update operations (including put() and remove()).

Creating a ConcurrentHashMap can be done as follows:

ConcurrentMap<Integer, Integer> map = new ConcurrentHashMap<>();
Whenever thread safety and high performance are required, you can rely on the thread-safe version of a Map , which is ConcurrentHashMap

Avoid Hashtable and Collections.synchronizedMap() since they have poor performance.

For a ConcurrentMap supporting NavigableMap, operations rely on ConcurrentSkipListMap:

ConcurrentNavigableMap<Integer, Integer> map 
= new ConcurrentSkipListMap<>();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset