Future is introduced in JDK 1.5 by Doug Lea to represent "the result of an asynchronous computation".
ExecutorService exe = Executors.newCachedThreadPool(); Runnable runnable = () -> System.out.println("Runnable"); Callable<String> callable = () -> "Callable"; exe.submit(runnable); Future<String> futureResult = exe.submit(callable); String result = futureResult.get(); System.out.println(result); exe.shutdown();
Similar to runnable, callable can also be submitted to executor service. Differently, callable is "A task that returns a result and may throw an exception."
The call to get a future result lead current thread to wait "if necessary for the computation to complete, and then retrieves its result." Below is one implementation of get method.
public final V get() throws InterruptedException, ExecutionException { int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ? doJoin() : externalInterruptibleAwaitDone(); Throwable ex; if ((s &= DONE_MASK) == CANCELLED) throw new CancellationException(); if (s == EXCEPTIONAL && (ex = getThrowableException()) != null) throw new ExecutionException(ex); return getRawResult(); }
In JDK 1.8, another future, CompletableFuture, is introduced by the same author with epoch-making significance. Completable future is "A {@link Future} that may be explicitly completed (setting its value and status), and may be used as a {@link CompletionStage}, supporting dependent functions and actions that trigger upon its completion."
Now it comes to the interesting part. Hey, what if we want to convert the legacy future into completable future so as to make full use of the new features?
Well, let‘s see an snippet from stack overflow http://stackoverflow.com/questions/23301598/transform-java-future-into-a-completablefuture
AsynchronousFileChannel open = AsynchronousFileChannel.open(Paths.get("/some/file")); // ... CompletableFuture<ByteBuffer> completableFuture = new CompletableFuture<ByteBuffer>(); open.read(buffer, position, null, new CompletionHandler<Integer, Void>() { @Override public void completed(Integer result, Void attachment) { completableFuture.complete(buffer); } @Override public void failed(Throwable exc, Void attachment) { completableFuture.completeExceptionally(exc); } }); completableFuture.thenApply(...)
If the 3rd party library support complete and fail callback, it‘s convinient to integrate with completable future. But usually, future inteferface won‘t contain these methods.
Hmmm, feels so close... and unreachable. Wait, how about ListenableFuture introduced by Guava ? It can add callback for a future.
ListeningExecutorService executor1 = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); ListenableFuture<Explosion> explosion = executor1.submit(new Callable<Explosion>() { public Explosion call() { return pushBigRedButton(); } }); Futures.addCallback(explosion, new FutureCallback<Explosion>() { // we want this handler to run immediately after we push the big red button! public void onSuccess(Explosion explosion) { walkAwayFrom(explosion); } public void onFailure(Throwable thrown) { battleArchNemesis(); // escaped the explosion! } }, executor2);
Pattern matched, problem solved, and everyone is happy now.
Do care about executor1 and executor2, configure the thread pools properly will boost the app performance, cheers~