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?
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
}
}
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