scala

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.


Solution

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