Is java.util.Hashtable thread safe?

后端 未结 9 1255
名媛妹妹
名媛妹妹 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:18

    If you look into Hashtable code, you will see that methods are synchronized such as:

    public synchronized V get(Object key) 
     public synchronized V put(K key, V value)
     public synchronized boolean containsKey(Object key)
    

    You can keep pressing on control key (command for mac) and then click on any method name in the eclipse to go to the java source code.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-09 07:23

    Unlike the new collection implementations, Hashtable is synchronized. *If a thread-safe implementation is not needed, it is recommended to use HashMap* in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

    http://download.oracle.com/javase/7/docs/api/java/util/Hashtable.html

    0 讨论(0)
提交回复
热议问题