search

Home  >  Q&A  >  body text

java - HashMap中在项目中不用锁,使用什么方法可以把他改造成线程安全的?

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

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

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

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

PHPzPHPz2894 days ago549

reply all(6)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:50:14

    The method mentioned by the poster is that you must lock it when CopyOnWrite吧,主要思想就是操作的时候创建一个副本,但是可以参照JDKCopyOnWriteArrayList,其实它set操作的时候也是有加锁的,在遍历的时候用的是副本,所以不用加锁操作.因为如果不加锁的,最后的数据merge回去是一件头疼的事情(意味着,你在merge)

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 09:50:14

    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

    reply
    0
  • 迷茫

    迷茫2017-04-18 09:50:14

    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.

    reply
    0
  • 黄舟

    黄舟2017-04-18 09:50:14

    Collections.synchronizedMap(Map)
    can be encapsulated as thread-safe

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:50:14

    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).

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 09:50:14

    Collections.synchronizedMap......?

    reply
    0
  • Cancelreply