Scala 线程安全的 HashSet [英] scala thread safe HashSet
问题描述
使 HashSet 线程安全的可能方法是什么?看到下面给出的一些样本.
What are the possible ways to make a HashSet thread safe? Saw some samples as given below.
var test = new mutable.HashSet[Long] with mutable.SynchronizedSet[Long]
SynchronizedSet 目前已弃用.任何建议或样本都会非常有帮助.
SynchronizedSet is deprecated at present. Any suggestions or samples will be very much helpful.
推荐答案
作为scala.collection.mutable.SynchronizedSet
建议,你可以使用 java.util.concurrent.ConcurrentHashMap[A, Unit]
代替.
如果你想让它看起来像一个 Set
而不是 Map
,那么你可以使用 java.util.Collections.newSetFromMap
在 Map
周围添加一个包装器,使其看起来像一个 Set
:
If you want it to look like a Set
instead of like a Map
, then you can use java.util.Collections.newSetFromMap
to add a wrapper around the Map
to make it look like a Set
:
def createSet[T]() = java.util.Collections.newSetFromMap(
new java.util.concurrent.ConcurrentHashMap[T, java.lang.Boolean])
然而,这将返回一个 Java Set
.您可以将其包装为 scala.collection.mutable.Set
:
This will, however, return a Java Set
. You can wrap this as a scala.collection.mutable.Set
:
def createSet[T]() = {
import scala.collection.JavaConverters._
java.util.Collections.newSetFromMap(
new java.util.concurrent.ConcurrentHashMap[T, java.lang.Boolean]).asScala
}
现在您可以使用特定类型的元素创建同步集合,例如 Long
,如下所示:
Now you can create a synchronized set with elements of a specific type, for example Long
, like this:
val set = createSet[Long]
这篇关于Scala 线程安全的 HashSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!