Java Concurrency

Concurrency

List

List list = new Vector<>();

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

Set

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

Map

Map map = Collections.SynchronizedMap(new HashMap<>());
Map 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) http://blog.sina.com.cn/s/blo...
(2) https://stackoverflow.com/que...
(3) https://www.bilibili.com/read...

你可能感兴趣的:(Java Concurrency)