How to timeout a message execution

Hi,

I am using akka actor to call a external function.

@Override
  public Receive createReceive() {
    return receiveBuilder()
        .matchEquals("execute", exeute -> {
              executeFunction();
        })
      .build();
  }

executeFunction will take any amount if time. we don’t have control over there. But I want to execute this in 30 seconds. How to interrupt a message execution or how to kill an actor in the middle of execution.

I went through akka doc where it mentioned that no option to kill an actor in-between message processing.

But I want this to be done in 30 sec if it exceeds I want to threw an timeout exception

Kindly guide me on this

Design it like this:

  • Create a child actor that runs executeFunction()
  • using the ask pattern, ask the child actor for the result of executeFunction() with a timeout of 30 seconds
  • When the result is obtained, or the ask timed out, kill the child actor

executeFunction will still complete, but that’s because there is no mechanism in Java/Scala to “undo” the call to a (blocking) method (unless you can interrupt the correct thread and the library supports InterruptedException, which is unlikely). So that problem is universal.

There are other improvements you can make to this pattern, but I think this is a good start.

2 Likes

Thank you so much @ignatius

As a bonus, if you want to fine-tune, you can create a dedicated dispatcher for this type of actor, to keep the blocking method call to executeFunction from depleting the system dispacher’s thread pool.

https://doc.akka.io/docs/akka/current/dispatchers.html

1 Like