本文介绍了Scala - 可变线程安全集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个可变线程安全地图和可变线程安全列表在Scala中。我知道默认情况下,不可变的集合是线程安全的。但是,我需要更新我的集合,因为我不能使用不变的。此外,我需要我的线程安全可变地图来维护插入顺序。

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.

现在正在使用下面的地图

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?

推荐答案



  1. 正如中提到的,如果你想要线程安全,你可以混合一个特征。还有另一种方法:

  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]


这应该可以让您 。容易,但可能不符合性能要求。如果是这样,创建一个扩展 LinkedHashMap 的自定义类可能更容易,在,并提供相关方法的实现,即: putIfAbsent 删除 替换(2重载) 。

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.Map trait (as was suggested) and provide the implementation of relevant methods, i.e: putIfAbsent, remove replace (2 overloads).

这篇关于Scala - 可变线程安全集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 14:25