Scala - Mutable thread safe collections

前端 未结 2 1995
有刺的猬
有刺的猬 2020-12-28 16:12

I need a mutable thread safe Map and a mutable thread safe List in Scala. I know that the immutable collections are thread safe by default. But, I need to update my collecti

相关标签:
2条回答
  • 2020-12-28 16:18

    Fast hint for those coming to this in 2018 or later:

    import java.util.concurrent.ConcurrentHashMap
    
    val m: ConcurrentHashMap[String,MyClass] = new ConcurrentHashMap
    
    0 讨论(0)
  • 2020-12-28 16:31
    1. You're duplicating topics....
    2. As was mentioned by AlexIv in his answer, there's a trait you can mix in if you want thread safety. There's another way though:

      val synchronizedMap = new scala.collection.mutable.LinkedHashMap[String, Any]() with scala.collection.mutable.SynchronizedMap[String, Any]
      

    That should give you the map with synchronization on each access. Easy, but might not meet the performance requirements. If so, it would be probably easier to create a custom class extending the LinkedHashMap, mixing in the concurrent.Map trait (as was suggested) and provide the implementation of relevant methods, i.e: putIfAbsent, remove replace (2 overloads).

    0 讨论(0)
提交回复
热议问题