看到很多文章说hashtable之所以被取代,原因在于它是线程同步的,因而效率比较低。
但是我在想,如果用不同步的HashMap,那当多个线程访问时,岂不是会出现数据不一致的现象?
所以我想hashtable被取代的前提是不是应该是在单线程环境下?
但是我在想,如果用不同步的HashMap,那当多个线程访问时,岂不是会出现数据不一致的现象?
所以我想hashtable被取代的前提是不是应该是在单线程环境下?
调试欢乐多
但很多测试表明,在高并发下HashTable并不是绝对线程安全。通常在多线程下是用ConcurrentHashMap来替代HashMap或HashTable。
java.util下集合类的Iterator迭代器都是线程不安全的,不光是HashTable,Vector也一样。如果你通过Iterator去并发修改(或修改的同时读取),同样会造成ConcurrentModificationException。
因为如果并发修改,就会造成冒其在未来某个不确定的时间,一个任意或不确定的表现的风险,这只能说明它的iterator是不允许被并发修改的而且在HashTable doc的最后一段,Vector也同样是这句话:
As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized.
可以相信HashTable是线程安全的吧
里面有些小的细节,我还不是很清楚,比如HashTable的
The Enumerations returned by Hashtable's keys and elements methods are not fail-fast.
既然其keys和elements方法返回的Enumerations不是fail-fast的,如何保证线程安全?除非它是允许并发修改的还有:
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
说fail-fast在非同步的并发修改下也不是有严格保证的,这些表述就让人有些疑惑了
参考下:
http://www.ibm.com/developerworks/cn/java/j-jtp09263/
http://www.ibm.com/developerworks/java/library/j-jtp08223/