smeeb
smeeb

Reputation: 29577

Sending behavior within Akka messages

Straight from the Akka docs:

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.

What's tripping me up is:

"...embracing this means to not routinely send behavior within messages..."

Can someone give me a concrete example of what they mean by "sending behavior within messages", and then explain how this is a violation of the "actor model"?

I'm using the Java API (not Scala), and so I only care about how this relates to Java 8.

Upvotes: 3

Views: 210

Answers (2)

Roland Kuhn
Roland Kuhn

Reputation: 15472

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 Actor referenced by someOther were to execute the behavior that we sent to it, then it would using our ActorContext, not its own. This will result in undefined behavior, it breaks the encapsulation. One Actor must not invoke any method on another Actor, ever. Only then can we guarantee that within an Actor you can program single-threadedly, without needing any synchronization primitives (like synchronized or locks/semaphores).

Upvotes: 3

Ryan
Ryan

Reputation: 7257

Don't send a function ("behavior") within a message because you might close over the internal state of another actor.

Upvotes: 2

Related Questions