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?
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.
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.
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.
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);
}
}
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