Actor 源码阅读之dispatcher

dispatch

分发器的核心函数是dispatch,代码如下:

protected[akka] def dispatch(receiver: ActorCell, invocation: Envelope): Unit = {
    val mbox = receiver.mailbox
    mbox.enqueue(receiver.self, invocation)
    registerForExecution(mbox, true, false)
  }

核心逻辑是获得接收者的邮箱,然后将消息放入邮箱中,然后将该邮箱注册到执行器。

registerForExecution

将邮箱注册到执行器的代码如下:

protected[akka] override def registerForExecution(
      mbox: Mailbox,
      hasMessageHint: Boolean,
      hasSystemMessageHint: Boolean): Boolean = {
    if (mbox.canBeScheduledForExecution(hasMessageHint, hasSystemMessageHint)) { //This needs to be here to ensure thread safety and no races
      if (mbox.setAsScheduled()) {
        try {
          executorService.execute(mbox)
          true
        } catch {
          case _: RejectedExecutionException =>
            try {
              executorService.execute(mbox)
              true
            } catch { //Retry once
              case e: RejectedExecutionException =>
                mbox.setAsIdle()
                eventStream.publish(Error(e, getClass.getName, getClass, "registerForExecution was rejected twice!"))
                throw e
            }
        }
      } else false
    } else false
  }

邮箱的本质是一个Runable,将邮箱注册到执行器的核心逻辑是将邮箱(Runable)提交到执行器服务执行。

你可能感兴趣的:(Akka,Actor源码阅读)