Akka ask returns nothing when tell is used in future - scala

The following code uses 2 asks and initially seems like it supposed to print "This should be printed in actor1 but most of the time wont because of a race condition with the receive method finishing".
However there seems to be a race condition between the 'receive' method finishing and the future finishing and thus nothing is printed.
Is this the intended behavior by akka? is this a bug?
I am trying to avoid using 'ask' as much as possible and using 'tell' instead, but sometimes it's a must.
import akka.actor._
import akka.routing.SmallestMailboxPool
import akka.util.Timeout
import akka.pattern.ask
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
object ActorsAskingStuff extends App {
val system = ActorSystem("abc-system")
val actor1 = system.actorOf(Props[Actor1].withRouter(SmallestMailboxPool(1)), "actor1")
actor1 ! 5
}
class Actor1 extends Actor {
implicit val timeout = Timeout(60 seconds)
val actor2: ActorRef = context.actorOf(Props[Actor2].withRouter(SmallestMailboxPool(1)), "actor2")
override def receive: Receive = {
case _ =>
println("actor1 was called")
actor2 ? "hello" onComplete {
case Success(a) => println(a)
case Failure(b) => println("FAILURE")
}
}
}
class Actor2 extends Actor {
implicit val timeout = Timeout(6 seconds)
val actor3: ActorRef = context.actorOf(Props[Actor3].withRouter(SmallestMailboxPool(1)), "actor3")
override def receive: Actor.Receive = {
case _ =>
println("actor2 was called")
actor3 ? "hello" map {
_ =>
println("Actor2 completed the future")
sender ! "This should be printed in actor1 but most of the time wont because of a race condition with the receive method finishing"
}
// uncomment this to make it work
//Thread.sleep(100)
}
}
class Actor3 extends Actor {
override def receive: Actor.Receive = {
case _ =>
println("actor3 was called")
sender ! "I'm actor3"
}
}

You are closing over the sender when you do this:
actor3 ? "hello" map {
_ =>
println("Actor2 completed the future")
sender ! "This should be printed in actor1 but most of the time wont because of a race condition with the receive method finishing"
}
At that point the sender could have changed. In order to avoid closing over the sender you can rewrite like this:
val originator = sender()
actor3 ? "hello" map {
_ =>
println("Actor2 completed the future")
originator ! "This should be printed in actor1 but most of the time wont because of a race condition with the receive method finishing"
}
Once you go into a Future based callback (like onComplete or map for example) at that point, the actor thinks it's done precessing the current message and moves onto the next message in the mailbox (if there is one). When this happens, the sender() which is just a def that returns the value of a var that is subject to change will return either a new ActorRef (more messages) or nothing (deadletter) if no messages.
You can checkout this post for more info:
sender inside a future

Related

I want to send second message to Actor as new Message

I have two actors for example, sender:
class ActorSender(actroReciever: ActorRef) extends Actor{
implicit val timeout = Timeout(100, TimeUnit.SECONDS)
override def receive: Receive = {
case "RUN" => {
val resp = Await.result(actroReciever ? "Msg", 100.seconds)
println("receive response " + resp)
};
case str:String => println(str)
case _ => println("Error type msg")
}
}
reciever:
class ActroReciever extends Actor{
override def receive: Receive = {
case str:String => {
val snd = sender()
snd ! "MessageFirst"
snd ! "MessageSecond"
}
}
}
And class for starting:
object Tester extends App {
val system = ActorSystem("system")
val receiver = system.actorOf(Props[ActroReciever](new ActroReciever()), "receiver")
val sender = system.actorOf(Props[ActorSender](new ActorSender(receiver)), "sender")
sender ! "RUN"
}
I want to send two messages to sender(), first as reply for "ask", second msg as "new Message", which ActorSender execute as "matching", how I can do it? Thanks
First, you know you should not use Await, right?
Second, ask (?) is not meant to be used within actors. ask creates a temporary actor which can only receive a single message. It is not your ActorSender receiving the answer, but the temporary actor created by ask. That's why you have the feeling you can only send 1 answer.
You are doing this wrong, you should simply send your message using actroReciever ! "Msg". No need to change anything on your ActroReciever.

context.become changes the behaviour of Akka Actor

I'm learning how to use context.become to control the state of my actor, i'm using this code:
class MyActor extends Actor {
override def receive: Receive = {
println("Happens here")
active(Set.empty)
}
def active(isInSet: Set[String]): Receive = {
case Add(key) =>
context.become(active(isInSet+key))
case Contains(key) =>
sender() ! isInSet(key)
case ShowAll =>
println(isInSet.toSeq)
}
}
case class Add(key: String)
case class Contains(key: String)
object ShowAll
object DemoBecome extends App{
override def main(args: Array[String]): Unit = {
val system = ActorSystem("BecomeUnbecome")
val act = system.actorOf(Props(classOf[MyActor]), "demoActor")
act ! Add("1")
act ! ShowAll
act ! Add("2")
act ! ShowAll
Thread.sleep(10000)
System.exit(0)
}
When i send the first message, the "receive" works and prints the message, after the second message doesn't show, this is my output:
Happens here
Set()
Vector(1)
Set(1)
Vector(1, 2)
If i change the receive method, for this:
def receive = {
case a: Add => println("happens here Add" )
case c: Contains => println("happens here Contains")
case ShowAll => println("happens here Show")
}
I receive this output:
happens here Add
happens here Show
happens here Add
happens here Show
So i tried, to track the moment when "receive" is "blocked", but i didn't have success, my doubt is: When i uses context.become in my actor, how and when Akka handle the messages after the first one?
When you use context.become you are changing the behavior in your actor. That means, when the actor starts it using the default receive behavior. However, when it receives a message it prints the message Happens here and uses the partial function active to handle it.
Since, inside active you call context.become(active(_)) the behavior of the actor changes. From now on, when a messages gets sent to the actor it will execute the partial function active instead of the receive method and that's why you are not seeing Happens here more than once in your output.

Resolving Akka futures from ask in the event of a failure

I am calling an Actor using the ask pattern within a Spray application, and returning the result as the HTTP response. I map failures from the actor to a custom error code.
val authActor = context.actorOf(Props[AuthenticationActor])
callService((authActor ? TokenAuthenticationRequest(token)).mapTo[LoggedInUser]) { user =>
complete(StatusCodes.OK, user)
}
def callService[T](f: => Future[T])(cb: T => RequestContext => Unit) = {
onComplete(f) {
case Success(value: T) => cb(value)
case Failure(ex: ServiceException) => complete(ex.statusCode, ex.errorMessage)
case e => complete(StatusCodes.InternalServerError, "Unable to complete the request. Please try again later.")
//In reality this returns a custom error object.
}
}
This works correctly when the authActor sends a failure, but if the authActor throws an exception, nothing happens until the ask timeout completes. For example:
override def receive: Receive = {
case _ => throw new ServiceException(ErrorCodes.AuthenticationFailed, "No valid session was found for that token")
}
I know that the Akka docs say that
To complete the future with an exception you need send a Failure message to the sender. This is not done automatically when an actor throws an exception while processing a message.
But given that I use asks for a lot of the interface between the Spray routing actors and the service actors, I would rather not wrap the receive part of every child actor with a try/catch. Is there a better way to achieve automatic handling of exceptions in child actors, and immediately resolve the future in the event of an exception?
Edit: this is my current solution. However, it's quite messy to do this for every child actor.
override def receive: Receive = {
case default =>
try {
default match {
case _ => throw new ServiceException("")//Actual code would go here
}
}
catch {
case se: ServiceException =>
logger.error("Service error raised:", se)
sender ! Failure(se)
case ex: Exception =>
sender ! Failure(ex)
throw ex
}
}
That way if it's an expected error (i.e. ServiceException), it's handled by creating a failure. If it's unexpected, it returns a failure immediately so the future is resolved, but then throws the exception so it can still be handled by the SupervisorStrategy.
If you want a way to provide automatic sending of a response back to the sender in case of an unexpected exception, then something like this could work for you:
trait FailurePropatingActor extends Actor{
override def preRestart(reason:Throwable, message:Option[Any]){
super.preRestart(reason, message)
sender() ! Status.Failure(reason)
}
}
We override preRestart and propagate the failure back to the sender as a Status.Failure which will cause an upstream Future to be failed. Also, it's important to call super.preRestart here as that's where child stopping happens. Using this in an actor looks something like this:
case class GetElement(list:List[Int], index:Int)
class MySimpleActor extends FailurePropatingActor {
def receive = {
case GetElement(list, i) =>
val result = list(i)
sender() ! result
}
}
If I was to call an instance of this actor like so:
import akka.pattern.ask
import concurrent.duration._
val system = ActorSystem("test")
import system.dispatcher
implicit val timeout = Timeout(2 seconds)
val ref = system.actorOf(Props[MySimpleActor])
val fut = ref ? GetElement(List(1,2,3), 6)
fut onComplete{
case util.Success(result) =>
println(s"success: $result")
case util.Failure(ex) =>
println(s"FAIL: ${ex.getMessage}")
ex.printStackTrace()
}
Then it would properly hit my Failure block. Now, the code in that base trait works well when Futures are not involved in the actor that is extending that trait, like the simple actor here. But if you use Futures then you need to be careful as exceptions that happen in the Future don't cause restarts in the actor and also, in preRestart, the call to sender() will not return the correct ref because the actor has already moved into the next message. An actor like this shows that issue:
class MyBadFutureUsingActor extends FailurePropatingActor{
import context.dispatcher
def receive = {
case GetElement(list, i) =>
val orig = sender()
val fut = Future{
val result = list(i)
orig ! result
}
}
}
If we were to use this actor in the previous test code, we would always get a timeout in the failure situation. To mitigate that, you need to pipe the results of futures back to the sender like so:
class MyGoodFutureUsingActor extends FailurePropatingActor{
import context.dispatcher
import akka.pattern.pipe
def receive = {
case GetElement(list, i) =>
val fut = Future{
list(i)
}
fut pipeTo sender()
}
}
In this particular case, the actor itself is not restarted because it did not encounter an uncaught exception. Now, if your actor needed to do some additional processing after the future, you can pipe back to self and explicitly fail when you get a Status.Failure:
class MyGoodFutureUsingActor extends FailurePropatingActor{
import context.dispatcher
import akka.pattern.pipe
def receive = {
case GetElement(list, i) =>
val fut = Future{
list(i)
}
fut.to(self, sender())
case d:Double =>
sender() ! d * 2
case Status.Failure(ex) =>
throw ex
}
}
If that behavior becomes common, you can make it available to whatever actors need it like so:
trait StatusFailureHandling{ me:Actor =>
def failureHandling:Receive = {
case Status.Failure(ex) =>
throw ex
}
}
class MyGoodFutureUsingActor extends FailurePropatingActor with StatusFailureHandling{
import context.dispatcher
import akka.pattern.pipe
def receive = myReceive orElse failureHandling
def myReceive:Receive = {
case GetElement(list, i) =>
val fut = Future{
list(i)
}
fut.to(self, sender())
case d:Double =>
sender() ! d * 2
}
}

How to send iterables between actors or from an actor to a Future?

A future from the main method of a program sends a msg to its actor asking for an iterable object. The actor then creates another future that asks for the iterable object (say an ArrayBuffer) from a remote actor. After receiving the ArrayBuffer from the remote actor, how would the actor send it back to the first future in the main method? It seems creating a local alias of sender and creating a separate case class to represent the iterable does not prevent dead letters from being encountered.
Here is a sample code:
case class SequenceObject(sqnce:Seq[someArrayBuffer])
//...
implicit val timeout = Timeout(10 seconds)
val fut1: Future[Any] = myActor ? iNeedAnArrayBufferObject
fut1.onSuccess {
case listOfItems: SequenceObject => {
//do sth with listofItems.sqnce
}
class myActor extends Actor {
implicit val timeout = Timeout(1 seconds)
def receive = {
case a: iNeedAnArrayBufferObject => {
val originalSender = sender
val fut: Future[Any] = (remoteActor ? a)
fut.onSuccess {
case list: SequenceObject => {
originalSender ! SequenceObject(list.sqnce)
}
}
The remote actor code is:
class ServerActorClass extends Actor {
def receive = {
case a: iNeedAnArrayBufferObject => {
val closer = sender()
closer ! SequenceObject(ArrayBufferObject[information])
}
}
The above does not seem to work. The remote actor and the local actor can communicate and messages are received correctly. However, the iterable object is never send back to fut1. Why is that? Thanks in advance.
Check pipeTo pattern in Ask: Send-And-Receive-Future section

How to send a delayed response inside Scala actor

Non-actor class sends a synchronous message to actor like this:
val response = WorkData !? "hello"
If i want to respond to this message right away, than i will do this:
receive {
case "hello" => reply("world")
}
But if i need to reply some time in the future, than
how do i store the caller reference, and send the reply after that?
Reference to the current caller is stored at sender. E.g., it's perfectly valid to replace
receive {
case "hello" => reply("world")
}
with
receive {
case "hello" => sender ! "world"
}
You can store this ref hereafter in the mutable variable, or pass recursively through the actor's loop.
I generally store the sender reference to use it later.
receive {
case "hello" =>
val otherParty = sender
// more receives, etc
// ...
otherParty ! "world"
}
How about just spawning an anonymous actor that processes the message and respond when it's ready? This way the receiver just acts as a dispatcher. This does not need a mutable variable to store anything since you are using a closure here.
import scala.actors.Actor
import scala.actors.Actor._
case class Message(msg: String)
class MyReceiver extends Actor {
def act() {
react {
case Message(msg) =>
actor {
sender ! process(msg)
}
}
}
def process(msg: String): String =
"Result: " + msg
}
object Main {
def main(args: Array[String]) {
val a = new MyReceiver
a.start()
val res = a !? Message("foo")
println(res)
}
}
Regards, raichoo