Scala - Mutable thread safe collections
Solution 1
- You're duplicating topics....
-
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).
Solution 2
Fast hint for those coming to this in 2018 or later:
import java.util.concurrent.ConcurrentHashMap
val m: ConcurrentHashMap[String,MyClass] = new ConcurrentHashMap
Related videos on Youtube
yAsH
Men are from Mars. Women are from Venus. Computers are from hell
Updated on April 06, 2020Comments
-
yAsH about 4 years
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 collections very often because of which I couldn't use immutable. Also I need my threadsafe mutable Map to maintain the insertion order.
Right now am using the map below
val map = scala.collection.mutable.LinkedHashMap[String,Any]()
This map maintains the insertion order and is mutable. How do I make it thread safe?
-
4lex1v almost 11 yearspossible duplicate of Thread safe map which preserves the insertion order
-
om-nom-nom almost 11 years@AlexIv not a duplicate in complete sense -- rahul asks about List too
-
4lex1v almost 11 years@om-nom-nom anyway it could be modified, but create a new question is excess
-
-
tysonjh about 10 yearsIf you can stand a bit more work, use the
synchronized
method on the mutable collection directly where you need thread safety. It'll save you the performance hit that this mixin brings. E.g.someMap.synchronized { someMap += ("someKey", "anyValue") }
-
Patrick White over 8 yearsFor anyone new viewing this, the SynchronizedMap trait has been deprecated as not safe enough. Recommends using Java thread safe collections.
-
Patrick White over 8 yearsIt's a compiler warning when you build after mixing in this trait - not sure about a link
-
Jeremy Rodi over 6 years@Gepp: scala-lang.org/api/2.12.3/scala/collection/mutable/…: "(Since version 2.11.0) Synchronization via traits is deprecated as it is inherently unreliable. Consider
java.util.concurrent.ConcurrentHashMap
as an alternative." -
ianpojman over 3 yearsTrieMap is mutable, thread-safe, lock-free, and is not deprecated
-
Saurabh Gangamwar over 2 yearsIs it still valid in 2021?