Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ConcurrentHashMap work internally?

I was reading the official Oracle documentation about Concurrency in Java and I was wondering what could be the difference between a Collection returned by

public static <T> Collection<T> synchronizedCollection(Collection<T> c); 

and using for example a

ConcurrentHashMap. I'm assuming that I use synchronizedCollection(Collection<T> c) on a HashMap. I know that in general a synchronized collection is essentially just a decorator for my HashMap so it is obvious that a ConcurrentHashMap has something different in its internals. Do you have some information about those implementation details?

Edit: I realized that the source code is publicly available: ConcurrentHashMap.java

like image 497
Adam Arold Avatar asked Aug 03 '12 09:08

Adam Arold


People also ask

How is a ConcurrentHashMap implemented?

In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updated in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking.

What is the difference between HashMap and ConcurrentHashMap in terms of internal working?

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.

How does ConcurrentHashMap implement fine grained Synchronisation?

ConcurrentHashMap implements ConcurrentMap which provides the concurrency. Deep internally its iterators are designed to be used by only one thread at a time which maintains the synchronization. This map is used widely in concurrency.


1 Answers

I would read the source of ConcurrentHashMap as it is rather complicated in the detail. In short it has

  • Multiple partitions which can be locked independently. (16 by default)
  • Using concurrent Locks operations for thread safety instead of synchronized.
  • Has thread safe Iterators. synchronizedCollection's iterators are not thread safe.
  • Does not expose the internal locks. synchronizedCollection does.
like image 169
Peter Lawrey Avatar answered Sep 18 '22 18:09

Peter Lawrey