Guava provides many useful extensions for Java parallel programming Future, its main interface is ListenableFuture, and it extends statically with the help of Futures.
ListenableFuture inherited to Future allows us to add a callback function to return the value when the thread operation is completed or the method execution is returned immediately.
Add a callback function to ListenableFuture:
Futures.addCallback(ListenableFuture<V>, FutureCallback<V>, Executor)
Where FutureCallback is an interface containing onSuccess(V) and onFailure(Throwable).
Used as follows:
Futures.addCallback(ListenableFuture, new FutureCallback<Object>() { public void onSuccess(Object result) { System.out.printf("onSuccess with: %s%n", result); } public void onFailure(Throwable thrown) { System.out.printf("onFailure %s%n", thrown.getMessage()); }});At the same time, Futures in Guava also has:
Below is a test demo for Future:
@Testpublic void should_test_furture() throws Exception { ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); ListenableFuture future1 = service.submit(new Callable<Integer>() { public Integer call() throws InterruptedException { Thread.sleep(1000); System.out.println("call future 1."); return 1; } }); ListenableFuture future2 = service.submit(new Callable<Integer>() { public Integer call() throws InterruptedException { Thread.sleep(1000); System.out.println("call future 2."); // throw new RuntimeException("----call future 2."); return 2; } }); final ListenableFuture allFuture = Futures.allAsList(future1, future2); final ListenableFuture transform = Futures.transform(allFutures, new AsyncFunction<List<Integer>, Boolean>() { @Override public ListenableFuture apply(List<Integer> results) throws Exception { return Futures.immediateFuture(String.format("success future:%d", results.size())); } }); Futures.addCallback(transform, new FutureCallback<Object>() { public void onSuccess(Object result) { System.out.println(result.getClass()); System.out.printf("success with: %s%n", result); } public void onFailure(Throwable thrown) { System.out.printf("onFailure%s%n", thrown.getMessage()); } }); System.out.println(transform.get());}Official information homepage: https://awk.so/@code.google.com!/p/guava-libraries/wiki/ListenableFutureExplained
The above is the information sorting out Guava - Parallel Programming Futures. We will continue to add relevant information in the future. Thank you for your support for this website!