BAR
BAR

Reputation: 17151

Sending Messages From Non-Actors in 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);
    }
}

Upvotes: 7

Views: 2915

Answers (4)

JRo
JRo

Reputation: 23

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 !

Upvotes: 1

Martina
Martina

Reputation: 174

The null as sender means that the receiving actor cannot execute sender().tell() to answer your message.

Upvotes: 0

Arseniy Zhizhelev
Arseniy Zhizhelev

Reputation: 2401

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.

Upvotes: 7

rs_atl
rs_atl

Reputation: 8985

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.

Upvotes: 1

Related Questions