Anton Gildebrand
Anton Gildebrand

Reputation: 3707

Scala synchronization best practice

I've started to learn Scala and Akka as the actor model. In an imperative language like C for example i can use several different methods for synchronizing threads on for example a binary tree; a simple semaphore or a mutex, atomic operations, and so on.

Scala however, is a functional object oriented language which can implement an actor model utilizing the Akka library (for example). How should synchronization be implemented in Scala? Let's say that i have i binary tree which my program is suppose to traverse and perform different operations upon. How should i make sure that two different actors isn't, for example, deleting the same node simultaniously?

Upvotes: 2

Views: 7157

Answers (2)

Richard Close
Richard Close

Reputation: 1905

If you want to do synchonized access to data structures, just use the synchronized method of AnyRef to synchronize a block. For example:

object Test {
  private val myMap = collection.mutable.Map.empty[Int, Int]
  def set(key: Int, value: Int): Unit = synchronized { myMap(key) = value }
  def get(key: Int): Option[Int] = synchronized { myMap.get(key) }
}

However, the point of using actors is to avoid threads blocking one another, which would hurt scalability. The Actor way of managing mutable state is for state to be private to Actor instances, and only updated or accessed in response to messages. This is a more complex design, something like:

// define case classes Get, Set, Value here.
class MapHolderActor extends Actor {
  private val myMap = collection.mutable.Map.empty[Int, Int] 
  def receive {
    case Get(key) => sender ! Value(myMap.get(key))
    case Set(key, value) => myMap(key) = value
  }
}

Upvotes: 9

om-nom-nom
om-nom-nom

Reputation: 62855

  1. On a high level you can use Actor as a mutex: it processes all incoming messages one by one.
  2. On the lower levels (but not at the actor level), nothing stops you from using plain old java concurrency primitives
  3. Use immutable data structures, as @Tanmay proposed, so there will be no in-place modification, thus no data races
  4. There are transactors (although deprecated in the very recent akka versions)

Upvotes: 5

Related Questions