在java中,Hashmap是线程不安全的,通过锁的机制和粒度,在源码中提供了HashTable和ConcurrentHashMap两种数据结构供使用,但是如果不使用锁,有什么方法将HashMap做到再业务中是线程安全的呢?
==========================================================================
我有一种思路是这样的:首先有一个map,再使用它的时候,将他赋值给一个新的map,我们叫他map',然后再将该map'做为key,存成一个新map。新map为Map<map',value>,这样每次添加的时候,是基于map'来添加的?
各路大神,还有没有其他思路呢?大家一起来讨论讨论哈。
The method mentioned by the poster is that you must lock it when
CopyOnWrite
吧,主要思想就是操作的时候创建一个副本,但是可以参照JDK
的CopyOnWriteArrayList
,其实它set
操作的时候也是有加锁的,在遍历的时候用的是副本,所以不用加锁操作.因为如果不加锁的,最后的数据merge回去是一件头疼的事情(意味着,你在merge
)Shared data cannot be thread-safe without locks. Your method's copying step is thread-unsafe.
To be thread safe, either don’t share or use locks
A copy is operated every time, so how to ensure that all threads are visible after each processing? And if it is added based on map', it may cause problems with database transactions, such as non-rereading and updating after adding thread A. Without map, thread B is overwritten with a new map'; if thread visibility is not required, use ThreadLocal for variable localization.
Collections.synchronizedMap(Map)
can be encapsulated as thread-safe
Thread safety cannot be achieved without using locks. It just depends on how advanced your lock is.
HashTable Because all operations of object locks will be synchronized, this is the most basic application.
The lock of ConcurrentHashMap is relatively advanced, because it implements a partition-like function internally and stores different keys in different areas. This implementation allows multiple threads to operate ConcurrentHashMap at the same time, but the same area can only be operated by a single thread. Operation(Lock).
Collections.synchronizedMap......?