How doe I get a concurrent or thread-safe Map
in Scala whose keys are weak? For example, there is collection.mutable.WeakHashMap
but it doesn't seem to support concurrent access/update. A cheap solution would be to hide it behind a regular Java synchronized lock?
1 Answer
Use Guava's MapMaker.
An example from the doc shows exactly what you need (translated into Scala):
import java.util.concurrent.ConcurrentMap
val timers: ConcurrentMap[Request, Stopwatch] =
new MapMaker().concurrencyLevel(4).weakKeys.makeMap
This is, of course, Java map, but you can easily wrap it into Scala map:
import java.{util => ju}
import scala.collection.JavaConverters._
import scala.collection.mutable
val javaMap: ju.Map[String,String] = ...
val scalaMap: mutable.Map[String,String] = javaMap.asScala
-
Ok, but is there something less heavy-weight than drawing in a complete third-party library?– 0__Commented Jul 13, 2014 at 10:30
-
@0__ If you want a map that is both concurrent (not just synchronized) and has weak keys then I don't think such implementation exists in standard libraries.– ghikCommented Jul 13, 2014 at 11:07