Actor系统的实体
在Actor系统中,actor之间具有树形的监管结构,并且actor可以跨多个网络节点进行透明通信。
对于一个Actor而言,其源码中存在Actor
,ActorContext
,ActorRef
等多个概念,它们都是为了描述Actor对象而进行的不同层面的抽象。
我们先给出一个官方的示例图,再对各个概念进行解释。
上图很清晰的展示了一个actor在源码层面的不同抽象,和不同actor之间的父子关系:
Actor类的一个成员context
是ActorContext类型,ActorContext存储了Actor类的上下文,包括self、sender。
ActorContext还混入了ActorRefFactory
特质,其中实现了actorOf
方法用来创建子actor。
这是Actor中context的源码:
trait Actor {
/**
* Stores the context for this actor, including self, and sender.
* It is implicit to support operations such as `forward`.
*
* WARNING: Only valid within the Actor itself, so do not close over it and
* publish it to other threads!
*
* [[akka.actor.ActorContext]] is the Scala API. `getContext` returns a
* [[akka.actor.UntypedActorContext]], which is the Java API of the actor
* context.
*/
implicit val context: ActorContext = {
val contextStack = ActorCell.contextStack.get
if ((contextStack.isEmpty) || (contextStack.head eq null))
throw ActorInitializationException(
s"You cannot create an instance of [${getClass.getName}] explicitly using the constructor (new). " +
"You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation.")
val c = contextStack.head
ActorCell.contextStack.set(null :: contextStack)
c
}
ActorCell的self
成员是ActorRef类型,ActorRef是一个actor的不可变,可序列化的句柄(handle),它可能不在本地或同一个ActorSystem中,它是实现网络空间位置透明性的关键设计。
这是ActorContext中self的源码:
trait ActorContext extends