Sending behavior in Akka messages

Straight from the Akka docs:

Actors are made containers for behavior and state, hugging this so as not to systematically dispatch behavior in messages (which can be tempting to use a Scala closure). One risk is the accidental sharing of mutable state among the participants, and this violation of the actor model unfortunately violates all the properties that make programming for actors such an enjoyable experience.

What turns me off:

"... covering this means you shouldn't post behavior regularly in posts ..."

Can someone give me a concrete example of what they mean by "represented behavior in posts" and then explain how this is a violation of the "actor model"?

I am using Java API (not Scala) and so I only care about how it relates to Java 8.

+3


source to share


2 answers


A concrete example using Java 8:

class MyActor extends AbstractActor {
  public MyActor(ActorRef someOther) {
    final Props props = Props.create(SomeActor.class);
    final PartialFunction<Object, BoxedUnit> behavior =
      ReceiveBuilder
        .match(String.class, s -> getContext().actorOf(props, s))
        .build();

    receive(ReceiveBuilder
      .matchAny(x -> someOther.tell(behavior, self()))
      .build()
    );
  }
}

      



If the referenced actor someOther

needs to perform the behavior we sent it, then it will use our ActorContext and not its own. This will lead to undefined behavior, it will break encapsulation. One Actor should not refer to any method on another Actor. Only then can we guarantee that within the Actor you can program in a single thread, without the need for any synchronization primitives (for example, synchronized

or locks / semaphores).

+3


source


Don't post a function ("behavior") in a message, because you might close another member's internal state.



+2


source







All Articles