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
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.
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.
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.
I would read the source of ConcurrentHashMap as it is rather complicated in the detail. In short it has
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With