簡體   English   中英

在 Akka 中發送來自非 Actor 的消息

[英]Sending Messages From Non-Actors in Akka

如果我打電話

actorRef.tell("MSG", null);

來自非演員

它仍然是線程安全的嗎? 和 async as in 立即完成?

消息是不可變的。

基本上我的代碼是:

class NonActor {
    ....

    public void tellTest() {

         actorRef.tell("MSG", null);
    }
}

基本上actorRef.tell("MSG", null); 創建一個記錄,如

(actorRef, Envelope(msg, sender))

並將其放入ActorSystem的消息隊列中。 因此, tell與演員沒有任何聯系。 tell方法本身無疑是線程安全的。

它是否是線程安全的取決於應用程序的其余部分。 Actor 本質上不是線程安全的; 您可以像與任何應用程序實體一樣共享可變狀態。 但是tell調用將立即返回,因為它是異步的。

只需使用! 操作員。

它在 Akka classic 2.6 中是這樣定義的:

trait ScalaActorRef { ref: ActorRef =>

  /**
   * Sends a one-way asynchronous message. E.g. fire-and-forget semantics.
   * <p/>
   *
   * If invoked from within an actor then the actor reference is implicitly passed on as the implicit 'sender' argument.
   * <p/>
   *
   * This actor 'sender' reference is then available in the receiving actor in the 'sender()' member variable,
   * if invoked from within an Actor. If not then no sender is available.
   * <pre>
   *   actor ! message
   * </pre>
   * <p/>
   */
  def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit

}

actorRef.tell("MSG", null)就像actorRef.!("MSG")(null) ,它強制發送者為null

如果您使用! 在 Actor 之外,將找不到隱式發送者,因此默認值Actor.noSender將由編譯器放置。

只要應該在編譯時自動解決發送者的缺失,明確告訴 Akka 它是null可能容易出錯。

永遠不要使用null是 Scala !

作為發送方的 null 意味着接收方無法執行 sender().tell() 來回答您的消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM