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);
}
}
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.
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.
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 null
could be bug prone.
Never use null
is Scala !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With