Asynchronous Programming in Java when using blocking APIs -
this question has answer here:
i working on java project uses apis blocking.
i use asynchronous programming , callbacks, don't have block while waiting result. i've looked using java future
, way think use calling get()
method block. open using other ways asynchronous programming well.
my current code looks this.
object res = blockingapi(); sendtoclient(res);
if use future
, this. understanding get()
blocking.
private final int threads = runtime.getruntime().availableprocessors(); private executorservice executor = executors.newfixedthreadpool(threads); public void invokeapi() { future<object> future = executor.submit(new callable<object>() { public object call() { return result; } }); object result = future.get(5, timeunit.seconds) }
how go implementing such function of get()
handled callback automatically gets invoked when result available?
several options.
one wrap future completablefuture:
public static <t> completablefuture<t> makecompletablefuture(future<t> future) { return completablefuture.supplyasync(() -> { try { return future.get(); } catch (interruptedexception|executionexception e) { throw new runtimeexception(e); } }); }
an other 1 use guava listenablefuture
:
listeningexecutorservice service = moreexecutors.listeningdecorator(executor); listenablefuture<t> future = service.submit(callable); futures.addcallback(future, new futurecallback<t>() { public void onsuccess(t t) { // ... } public void onfailure(throwable thrown) { // ... } });
you can use akka futures highly composable.
Comments
Post a Comment