Is java.util.Hashtable thread safe?

后端 未结 9 1274
名媛妹妹
名媛妹妹 2020-12-09 06:23

It\'s been a while since I\'ve used hashtable for anything significant, but I seem to recall the get() and put() methods being synchronized.

The JavaDocs don\'t ref

9条回答
  •  臣服心动
    2020-12-09 07:22

    Hashtable is deprecated. Forget it. If you want to use synchronized collections, use Collections.syncrhonize*() wrapper for that purpose. But these ones are not recommended. In Java 5, 6 new concurrent algorithms have been implemented. Copy-on-write, CAS, lock-free algorithms. For Map interface there are two concurrent implementations. ConcurrentHashMap (concurrent hash map) and ConcurrentSkipListMap - concurrent sorted map implementaion.

    The first one is optimized for reading, so retrievals do not block even while the table is being updated. Writes are also work much faster comparing with synchronized wrappers cause a ConcurrentHashMap consists of not one but a set of tables, called segments. It can be managed by the last argument in the constructor:

    public ConcurrentHashMap(int initialCapacity,
                             float loadFactor,
                             int concurrencyLevel);
    

    ConcurrentHashMap is indispensable in highly concurrent contexts, where it performs far better than any available alternative.

提交回复
热议问题