What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

前端 未结 19 1134
名媛妹妹
名媛妹妹 2020-11-22 11:45

I have a Map which is to be modified by several threads concurrently.

There seem to be three different synchronized Map implementations in the Java API:

    <
19条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 12:12

    ╔═══════════════╦═══════════════════╦═══════════════════╦═════════════════════╗
    ║   Property    ║     HashMap       ║    Hashtable      ║  ConcurrentHashMap  ║
    ╠═══════════════╬═══════════════════╬═══════════════════╩═════════════════════╣ 
    ║      Null     ║     allowed       ║              not allowed                ║
    ║  values/keys  ║                   ║                                         ║
    ╠═══════════════╬═══════════════════╬═════════════════════════════════════════╣
    ║ Thread-safety ║                   ║                                         ║
    ║   features    ║       no          ║                  yes                    ║
    ╠═══════════════╬═══════════════════╬═══════════════════╦═════════════════════╣
    ║     Lock      ║       not         ║ locks the whole   ║ locks the portion   ║        
    ║  mechanism    ║    applicable     ║       map         ║                     ║ 
    ╠═══════════════╬═══════════════════╩═══════════════════╬═════════════════════╣
    ║   Iterator    ║               fail-fast               ║ weakly consistent   ║ 
    ╚═══════════════╩═══════════════════════════════════════╩═════════════════════╝
    

    Regarding locking mechanism: Hashtable locks the object, while ConcurrentHashMap locks only the bucket.

提交回复
热议问题