How to handle concurrent access to a Scala collection?

后端 未结 4 1942
悲哀的现实
悲哀的现实 2021-01-04 11:11

I have an Actor that - in its very essence - maintains a list of objects. It has three basic operations, an add, update and a remove (where sometimes the remove is called fr

相关标签:
4条回答
  • 2021-01-04 11:28

    Scala's immutable collections are suitable for concurrent usage.

    As for actors, a couple of things are guaranteed as explained here the Akka documentation.

    • the actor send rule: where the send of the message to an actor happens before the receive of the same actor.
    • the actor subsequent processing rule: where processing of one message happens before processing of the next message by the same actor.

    You are not guaranteed that the same thread processes the next message, but you are guaranteed that the current message will finish processing before the next one starts, and also that at any given time, only one thread is executing the receive method.

    So that takes care of a given Actor's persistent state. With regard to shared data, the best approach as I understand it is to use immutable data structures and lean on the Actor model as much as possible. That is, "do not communicate by sharing memory; share memory by communicating."

    0 讨论(0)
  • 2021-01-04 11:31

    You don't need to synchronize the state of the actors. The aim of the actors is to avoid tricky, error prone and hard to debug concurrent programming.

    Actor model will ensure that the actor will consume messages one by one and that you will never have two thread consuming message for the same Actor.

    0 讨论(0)
  • 2021-01-04 11:41

    What collection type should I use in a concurrent access situation, and how is it used?

    See @hbatista's answer.

    Is an Actor actually a multithreaded entity, or is that just my wrong conception and does it process messages one at a time in a single thread

    The second (though the thread on which messages are processed may change, so don't store anything in thread-local data). That's how the actor can maintain invariants on its state.

    0 讨论(0)
  • 2021-01-04 11:47

    Take a look at the scala.collection.mutable.Synchronized* traits/classes.

    The idea is that you mixin the Synchronized traits into regular mutable collections to get synchronized versions of them.

    For example:

    import scala.collection.mutable._
    val syncSet = new HashSet[Int] with SynchronizedSet[Int]
    val syncArray = new ArrayBuffer[Int] with SynchronizedBuffer[Int]
    
    0 讨论(0)
提交回复
热议问题