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?
One advantage of an immutable collection is that it is automatically thread safe. After you create a collection, you can hand it to multiple threads, and they will all see a consistent view. However, an immutable collection of objects is not the same as a collection of immutable objects.
To get a thread-safe mutable map, you can mix the SynchronizedMap trait trait into whatever particular map implementation you desire.
Unfortunately, in its current state released in Scala 2.10. 0, reflection is not thread safe. There's a JIRA issue SI-6240, which can be used to track our progress and to look up technical details, and here's a concise summary of the state of the art. NEW Thread safety issues have been fixed in Scala 2.11.
Scala collections systematically distinguish between mutable and immutable collections. A mutable collection can be updated or extended in place. This means you can change, add, or remove elements of a collection as a side effect. Immutable collections, by contrast, never change.
Fast hint for those coming to this in 2018 or later:
import java.util.concurrent.ConcurrentHashMap val m: ConcurrentHashMap[String,MyClass] = new ConcurrentHashMap
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With