Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Future onSuccess as response from an Akka actor

Tags:

java

akka

This is the code that works. It send a message to an Actor (Greeter) and wait for the answer back. But it blocks the current thread.

public class Future1Blocking {

    public static void main(String[] args) throws Exception {

        ActorSystem system = ActorSystem.create("system");
        final ActorRef actorRef = system.actorOf(Props.create(Greeter.class), "greeter");

        Timeout timeout = new Timeout(Duration.create(5, "seconds"));
        Future<Object> future = Patterns.ask(actorRef, Greeter.Msg.GREET, timeout);

        // this blocks current running thread
        Greeter.Msg result = (Greeter.Msg) Await.result(future, timeout.duration());

        System.out.println(result);

    }
}

What is the possible way for my example to use future.onSuccess to get the result without blocking the current calling thread?

like image 592
ses Avatar asked May 17 '13 15:05

ses


People also ask

What is Future in Akka?

Introduction. In the Scala Standard Library, a Future is a data structure used to retrieve the result of some concurrent operation. This result can be accessed synchronously (blocking) or asynchronously (non-blocking). To be able to use this from Java, Akka provides a java friendly interface in akka.

Can an Akka actor stop other actors?

In Akka, you can stop Actors by invoking the stop() method of either ActorContext or ActorSystem class. ActorContext is used to stop child actor and ActorSystem is used to stop top level Actor.

How does Akka handle concurrency?

Akka's approach to handling concurrency is based on the Actor Model. In an actor-based system, everything is an actor, in much the same way that everything is an object in object-oriented design.


1 Answers

Ahh. that's was easy (sorry).

future.onSuccess(new PrintResult<Object>(), system.dispatcher());

Where:

public final class PrintResult<T> extends OnSuccess<T> {
    @Override public final void onSuccess(T t) {
        System.out.println(t);
    }
}
like image 80
ses Avatar answered Sep 19 '22 00:09

ses