简体   繁体   中英

scala thread safe 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 is deprecated at present. Any suggestions or samples will be very much helpful.

As the API documentation of scala.collection.mutable.SynchronizedSet suggests, you can use java.util.concurrent.ConcurrentHashMap[A, Unit] instead.

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

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
}

Now you can create a synchronized set with elements of a specific type, for example Long , like this:

val set = createSet[Long]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM