java - HashMap中在项目中不用锁,使用什么方法可以把他改造成线程安全的?
PHPz
PHPz 2017-04-18 09:48:14
0
6
522

在java中,Hashmap是线程不安全的,通过锁的机制和粒度,在源码中提供了HashTable和ConcurrentHashMap两种数据结构供使用,但是如果不使用锁,有什么方法将HashMap做到再业务中是线程安全的呢?

==========================================================================

我有一种思路是这样的:首先有一个map,再使用它的时候,将他赋值给一个新的map,我们叫他map',然后再将该map'做为key,存成一个新map。新map为Map<map',value>,这样每次添加的时候,是基于map'来添加的?

各路大神,还有没有其他思路呢?大家一起来讨论讨论哈。

PHPz
PHPz

学习是最好的投资!

reply all(6)
Ty80

The method mentioned by the poster is that you must lock it when CopyOnWrite吧,主要思想就是操作的时候创建一个副本,但是可以参照JDKCopyOnWriteArrayList,其实它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......?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!