Akka 消息中的发送行为
Sending behavior within Akka messages
直接来自 Akka 文档:
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.
让我不爽的是:
"...embracing this means to not routinely send behavior within messages..."
谁能给我一个具体的例子来说明“在消息中发送行为”是什么意思,然后解释这是怎么回事违反了 "actor model"?
我正在使用 Java API(不是 Scala),所以我只关心它与 Java 8.[=23 的关系=]
不要在消息中发送函数 ("behavior"),因为您可能会关闭另一个参与者的内部状态。
使用Java8的具体例子:
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()
);
}
}
如果 someOther
引用的 Actor 执行我们发送给它的行为,那么它会使用 我们的 ActorContext,而不是它自己的。这将导致未定义的行为,它破坏了封装。一个 Actor 永远不能 调用另一个 Actor 的任何方法。只有这样我们才能保证在 Actor 中您可以单线程编程,而不需要任何同步原语(如 synchronized
或 locks/semaphores)。