yAsH
yAsH

Reputation: 3405

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?

Upvotes: 29

Views: 37867

Answers (3)

Patryk Ćwiek
Patryk Ćwiek

Reputation: 14318

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

Upvotes: 22

haagmm
haagmm

Reputation: 593

To elaborate on the comment for a Map you can use

import scala.collection.concurrent.TrieMap

Is not deprecated and is mutable and thread-safe.

It should drop in for your scala.collection.mutable.LinkedHashMap as they share the same interface of scala.collection.mutable.MapLike and scala.collection.mutable.Map

Sadly I don't know about the List

Upvotes: 1

akauppi
akauppi

Reputation: 18046

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

import java.util.concurrent.ConcurrentHashMap

val m: ConcurrentHashMap[String,MyClass] = new ConcurrentHashMap

Upvotes: 47

Related Questions