Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentHashMap, which concurrent features improved in JDK8

Can any concurrent expert explain in ConcurrentHashMap, which concurrent features improved comparing with which in previous JDKs

like image 654
taigetco Avatar asked Jul 23 '15 02:07

taigetco


People also ask

What is the use of ConcurrentHashMap () in multithreading?

ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications. At a time any number of threads are applicable for a read operation without locking the ConcurrentHashMap object which is not there in HashMap.

Which package offers improved support for concurrency compared to the direct usage of?

The `java. util. concurrent` package offers improved support for concurrency compared to the direct usage of `Threads`.

Which is better HashMap or ConcurrentHashMap?

HashMap is non-Synchronized in nature i.e. HashMap is not Thread-safe whereas ConcurrentHashMap is Thread-safe in nature. HashMap performance is relatively high because it is non-synchronized in nature and any number of threads can perform simultaneously.


1 Answers

Well, the ConcurrentHashMap has been entirely rewritten. Before Java 8, each ConcurrentHashMap had a “concurrency level” which was fixed at construction time. For compatibility reasons, there is still a constructor accepting such a level though not using it in the original way. The map was split into as many segments, as its concurrency level, each of them having its own lock, so in theory, there could be up to concurrency level concurrent updates, if they all happened to target different segments, which depends on the hashing.

In Java 8, each hash bucket can get updated individually, so as long as there are no hash collisions, there can be as many concurrent updates as its current capacity. This is in line with the new features like the compute methods which guaranty atomic updates, hence, locking of at least the hash bucket which gets updated. In the best case, they lock indeed only that single bucket.

Further, the ConcurrentHashMap benefits from the general hash improvements applied to all kind of hash maps. When there are hash collisions for a certain bucket, the implementation will resort to a sorted map like structure within that bucket, thus degrading to a O(log(n)) complexity rather than the O(n) complexity of the old implementation when searching the bucket.

like image 156
Holger Avatar answered Sep 20 '22 18:09

Holger