multithreading Scala - 可变线程安全集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17541355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 01:23:37  来源:igfitidea点击:

Scala - Mutable thread safe collections

multithreadingscalacollectionsmapthread-safety

提问by yAsH

I need a mutable thread safe Map and a mutable thread safe List in Scala. I know that the immutable collections are thread safe by default. But, I need to update my collections very often because of which I couldn't use immutable. Also I need my threadsafe mutable Map to maintain the insertion order.

我需要 Scala 中的可变线程安全映射和可变线程安全列表。我知道默认情况下不可变集合是线程安全的。但是,我需要经常更新我的收藏,因此我不能使用不可变的。我还需要我的线程安全可变 Map 来维护插入顺序。

Right now am using the map below

现在正在使用下面的地图

val map = scala.collection.mutable.LinkedHashMap[String,Any]()

This map maintains the insertion order and is mutable. How do I make it thread safe?

该映射保持插入顺序并且是可变的。我如何使它线程安全?

采纳答案by Patryk ?wiek

  1. You're duplicating topics....
  2. As was mentioned by AlexIv in his answer, there's a trait you can mix in if you want thread safety. There's another way though:

    val synchronizedMap = new scala.collection.mutable.LinkedHashMap[String, Any]() with scala.collection.mutable.SynchronizedMap[String, Any]
    
  1. 你在复制主题....
  2. 正如AlexIv 在他的回答中提到的,如果你想要线程安全,你可以混合一个特性。不过还有一种方法:

    val synchronizedMap = new scala.collection.mutable.LinkedHashMap[String, Any]() with scala.collection.mutable.SynchronizedMap[String, Any]
    

That should give you the map with synchronization on each access. Easy, but might not meet the performance requirements. If so, it would be probably easier to create a custom class extending the LinkedHashMap, mixing in the concurrent.Maptrait (as was suggested)and provide the implementation of relevant methods, i.e: putIfAbsent, removereplace(2 overloads).

这应该为您提供每次访问同步地图。简单,但可能无法满足性能要求。如果是这样,创建一个扩展LinkedHashMap, 混合concurrent.Map特征的自定义类(如建议的那样)并提供相关方法的实现可能会更容易,即:putIfAbsentremovereplace(2 个重载)。

回答by akauppi

Fast hint for those coming to this in 2018 or later:

给那些在 2018 年或以后参与的人的快速提示:

import java.util.concurrent.ConcurrentHashMap

val m: ConcurrentHashMap[String,MyClass] = new ConcurrentHashMap