Does a ConcurrentHashMap need to be wrapped in a synchronized block?

后端 未结 2 1365
野性不改
野性不改 2020-12-24 01:39

Do all non-retreival operations on a ConcurrentHashMap (put(), remove() etc.) need to be wrapped in a synchronized(this) block? I und

2条回答
  •  青春惊慌失措
    2020-12-24 02:04

    Synchronizing those operations has no benefit here - it actually degrades performance if you don't need synchronization.

    The reason ConcurrentHashMap was created, is that synchronized maps (either implemented by hand like in the question or instantiated in the usual way with Collections.synchronizedMap(map)) show bad performance when accessed by many threads. Put and get operations are blocking, so all other threads have to wait and can't access the map concurrently. The ConcurrentHashMap - as the name suggest - allows concurrent access on the other hand. You lose this benefit if you add synchronization.

提交回复
热议问题