日期:2014-05-17  浏览次数:21258 次

HashTable真的是线程安全吗?
刚才看了HashTable源码,没有发现HashTable哪里使用同步保证线程安全的?难道是我看错了吗?


public Object put(Object key, Object value) {
        // Make sure the value is not null
        if (value == null) throw new NullPointerException();

        // Makes sure the key is not already in the hashtable.
        HashtableEntry e;
        HashtableEntry tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;

        for (e = tab[index] ; e != null ; e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                Object old = e.value;
                e.value = value;
                return old;
            }
        }

        // Rehash the table if the threshold is exceeded
        if (count >= threshold) {
            rehash();
            return put(key, value);
        }

        // Creates the new entry.
        e = new HashtableEntry();
        e.hash = hash;
        e.key = key;
        e.value = value;
        e.next = tab[index];
        tab[index] = e;
        count++;
        return null;
    }
上面是源码
------解决方案--------------------
好多面试题都说hashmap不是线程安全的,hashtable才是。。。然后我也这么答了。。
------解决方案--------------------
还有arraylist和vector,也是死记硬背的。到现在就没用过vector和hashtable
------解决方案--------------------
一般是较早之前有的都是线程安全的!
------解决方案--------------------
请问楼主这段代码是哪个版本的jdk的?怎么看着这么不对劲儿呢?
------解决方案--------------------
引用:
一般是较早之前有的都是线程安全的!



这个说的是对的,版本比较低的 集合都是&n