HoistTheColorsAndStepToTheRail

HoistTheColorsAndStepToTheRail

Concurrency

List

List<String> list = new Vector<>();

List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList<>();

Set

Set<String> set = Collections.synchronizedSet(new HashSet<>());
Set<String> set = new CopyOnWriteArraySet<>();

Map

Map<String, String> map = Collections.SynchronizedMap(new HashMap<>());
Map<String, String> map = new ConcurrentHashMap<>();

SynchronizedMap

It will maintain the lock at the object level. So if you want to perform any operation like put/get then you have to aquire the lock first. At the same time, other threads are not allowed to perfrom any operaton. So the waiting time will increase here. We can say the performance is relatively low when comparing with ConcurrentHashMap.

ConcurrentHashMap

Using finer-grained locking mechanism known as Locking Stripping to allow greater degree of shared access. Due to this it provides better concurrency and scalability.

It will maintain the lock at segment level. It has 16 segments and maintains the concurrency level as 16 by default. So at a time, 16 threads can operate on ConcurrentHashMap. Moreover, read operation doesn’t require a lock, so any number of threads can perform a get operation on it.

Using finer-grained locking mechanism known as Locking Stripping to allow greater degree of shared access. Due to this it provides better concurrency and scalability.

Weak consistency: Iterators returned for ConcurrentHashMap are weakly consistent instead of fail-fast technique used by SynchronizedMap.

Ref

(1) HashTable、ConcurrentHashMap、SynchronizedMap(都是线程安全的)
(2) ConcurrentHashMap vs Synchronized HashMap
(3) ConcurrentHashMap、Hashtable 和 Synchronized Map 的不同之处

03-05 14:50