Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala thread safe HashSet

Tags:

scala

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.

like image 714
Prakash Avatar asked Dec 06 '16 10:12

Prakash


1 Answers

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]
like image 114
Jesper Avatar answered Oct 05 '22 13:10

Jesper