简体   繁体   中英

Can we have global state in actor-based systems?

One of the biggest advantages of the actor model is the removal of locking (actors operate independently and serially). Does this mean that we cannot have any shared/global state at all in an actor system (because accessing/updating that will bring in locks)?

In more practical terms, what happens to updates to an entity (eg DB) from multiple actors in such a system?

Actor model intended to solve issue with any mutable shared state in another way - actor should encapsulate it. So if you need something to be shared between actors - this should be an actor with this state and protocol to work with it. If you would like to update DB from different actors - extract an actor responsible for this, and provide API or protocol for other actors to update DB. Or make several actors to handle DB updates and route messages between them (Please, see for more details: https://doc.akka.io/docs/akka/current/typed/routers.html )

General approach - think about shared state, as actor shared between actors (via ActorRef ) and state API as messages for this actor.

Usually, it is not a preferred way to have a shared/global state in an actor system. A very central idea when working with actors is to not share any mutable state, instead, mutable state is encapsulated inside of the actors as pointed out in the documanetation

Do not pass mutable objects between actors. In order to ensure that, prefer immutable messages. If the encapsulation of actors is broken by exposing their mutable state to the outside, you are back in normal Java concurrency land with all the drawbacks.

Actors are made to be containers for behavior and state, embracing this means to not routinely send behavior within messages (which may be tempting using Scala closures). One of the risks is to accidentally share mutable state between actors, and this violation of the actor model unfortunately breaks all the properties which make programming in actors such a nice experience.

Moreover, If one actor needs to know something about the state of another actor it will ask for it using immutable messages and get an immutable reply.One of the key features of Akka actors its their ability to manage state in a thread-safe manner and by having a shared and mutable state, we will violate this property

Usually DB reading operations (CRUD) can be performed directly by any actor.To perform this. make an actor responsible for this, and use it from other actors.

Let me know if it helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM