How to handle concurrent access to a Scala collection?

后端 未结 4 1945
悲哀的现实
悲哀的现实 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."

提交回复
热议问题