Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Messages From Non-Actors in Akka

Tags:

java

akka

If I were to call

actorRef.tell("MSG", null);

From a non-actor

Is it still thread safe? And async as in completes immediately?

The message is immutable.

Basically my code is:

class NonActor {
    ....

    public void tellTest() {

         actorRef.tell("MSG", null);
    }
}
like image 359
BAR Avatar asked Sep 05 '13 20:09

BAR


3 Answers

Basically actorRef.tell("MSG", null); creates a record like

(actorRef, Envelope(msg, sender))

and put it into ActorSystem's message queue. Thus tell is not linked to the actor in any way. The tell method itself is undoubtedly thread-safe.

like image 191
Arseniy Zhizhelev Avatar answered Oct 19 '22 06:10

Arseniy Zhizhelev


Whether it's thread-safe depends on the rest of your app. Actors aren't inherently thread-safe; you can share mutable state just as you could with any application entity. But the tell call will return immediately because it's asynchronous.

like image 22
rs_atl Avatar answered Oct 19 '22 05:10

rs_atl


Just use the ! operator.

It is defined like this in 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) is like actorRef.!("MSG")(null), that forces the sender to be null.

If you use ! outside an Actor, the implicit sender won't be found thus the default value Actor.noSender will be put by the compiler.

As long as the absence of sender is supposed to be automatically resolved at compile time, explicitly telling Akka it is nullcould be bug prone.

Never use null is Scala !

like image 43
JRo Avatar answered Oct 19 '22 06:10

JRo