I am working on a Java project that uses certain APIs that are blocking.
I would like to use asynchronous programming and callbacks, so that I don't have to block while waiting for the result. I've looked into using Java Future
, but the only way I think I could use it is by calling the get()
method which would block. I am open to using other ways to do asynchronous programming as well.
My current code looks like this.
Object res = blockingAPI();
sendToClient(res);
If I were to use Future
, I would do it like this. But my understanding is get()
is 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 could I go about implementing this such that the function of get()
is basically handled by a callback that automatically gets invoked when the result is available?