Scala - 初始化一个空的可变 SynchronizedHashMap

Scala - Initialize an empty mutable SynchronizedHashMap

据我了解,我们可以将一个空的可变 HashMap 初始化为

var keyCountsMap :scala.collection.mutable.Map[Any, Int] = scala.collection.mutable.Map[Any, Int]()

但是如何将这个 HasMap 初始化为同步的呢? 我试过了

var keyCountsMap :scala.collection.mutable.SynchronizedMap[Any, Int] = scala.collection.mutable.Map[Any, Int]()

但我收到以下错误:

type mismatch; found : scala.collection.mutable.Map[Any,Int]
required: scala.collection.mutable.SynchronizedMap[Any,Int]

您可以混入 SynchronizedMap ( deprecated in 2.11 )

    var keyCountsMap = new scala.collection.mutable.HashMap[Any, Int]() with scala.collection.mutable.SynchronizedMap[Int, Int]

如果您查看文档,您会看到:

This class should be used as a mixin. It synchronizes the Map functions of the class into which it is mixed in.

Synchronization via traits is deprecated as it is inherently unreliable. Consider java.util.concurrent.ConcurrentHashMap as an alternative.