Asynchronous Programming in Java when using blocking APIs -


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

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -