【Developer Log】Thread-safe

来源:互联网 发布:魅族note5 网络制式 编辑:程序博客网 时间:2024/06/08 15:03

在web中采用多线程,多线程读写某个Collection,就会涉及thread-safe的问题,如果collection在操作的使用采用synchronize,那么这就是线程安全,但这是要付出性能代价的,也可以不适用thread-safe,但需要根据需求自己考虑是否加上同步。

在http://www.asjava.com/core-java/thread-safe-hash-map-in-java-and-their-performance-benchmark/中有对何为线程安全有详细的解析,增删entry是就涉及线程安全,仅仅修改key所对应的value不属于考虑范围(这可能和原子操作有关,无需担心)。

What does the thread safe Map means? If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally to avoid an inconsistent view of the contents. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)

对于List,Vector是线程安全,但是ArrayList不是。在javadoc中是这样描述Vector:

As of the Java 2 platform v1.2, this class was retrofitted to implement theList interface, making it a member of theJava Collections Framework. Unlike the new collection implementations,Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to useArrayList in place ofVector.

对于Map,Hashtable是线程安全的,但是HashMap不是。但是使用古老的Hashtable有时性能也真不好,而且Hashtable不允许null作为值,而HashMap允许。我们可以通过下面两种方式来实现。例如对于替代

Map<String, Integer> threadSafeMap = new Hashtable<String, Integer>();

方式1:采用Collections.synchronizedMap

Map<String,Integer>threadSafeMap = Collections.synchronizedMap(new HashMap<String, Integer>());

方式2:采用在Java 1.5引入的ConcurrentHashMap

Map<String,Integer> threadSafeMap = new ConcurrentHashMap<String, Integer>();

根据http://www.asjava.com/core-java/thread-safe-hash-map-in-java-and-their-performance-benchmark/的测试数据,ConcurrentHashMap的效率更高。因此,在我们需要thread-safe的使用,应该尽可能地使用ConcurrentHashMap

 

相关链接:开发日志

0 0
原创粉丝点击