Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - Mutable thread safe collections

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?

like image 684
yAsH Avatar asked Jul 09 '13 06:07

yAsH


People also ask

Are immutable collections 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.

Is mutable map thread-safe?

To get a thread-safe mutable map, you can mix the SynchronizedMap trait trait into whatever particular map implementation you desire.

Is Scala thread-safe?

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.

What are the mutable collections in Scala?

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.


2 Answers

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

import java.util.concurrent.ConcurrentHashMap  val m: ConcurrentHashMap[String,MyClass] = new ConcurrentHashMap 
like image 191
akauppi Avatar answered Oct 02 '22 20:10

akauppi


  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).

like image 26
Patryk Ćwiek Avatar answered Oct 02 '22 20:10

Patryk Ćwiek