【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。
相关链接:开发日志
- 【Developer Log】Thread-safe
- Thread-safe, Signal-safe
- thread safe
- PHP Thread Safe and Non Thread Safe
- Thread Safe In Servlet
- Python: Thread safe Oject
- Older Thread-Safe Collections
- Thread-Safe Interface
- Thread safe circular queue
- what is thread safe
- Spring thread safe
- Thread-Safe Random Numbers
- Java Thread-safe
- libcurl thread safe
- Thread-Safe Class Design
- thread safe vs reentrant
- Is errno thread-safe ?
- [LinkedIn] singleton, thread safe
- VC 中使用 WebBrowser 控件时自定义 User-Agent 的方法
- 求解二叉树的深度(递归和非递归)
- Android Activity学习笔记——Activity的启动和创建
- 富文本内图片 尺寸 宽度 自适应效果
- HDU-4570 Multi-bit Trie (DP)
- 【Developer Log】Thread-safe
- Android适配全攻略(学习笔记总结)
- 网卡的基础知识
- [精]免费SSL(https)证书申请之startssl
- js生成二维码实例(真实有效)
- Hbase javaapi curd笔记
- 焦距
- webserver.c Simple HTTP server sample for sanos
- 写给2016年开始步入开发工作的新宝宝们