Skip to content

Instantly share code, notes, and snippets.

@benjchristensen
Last active December 11, 2015 22:39
Show Gist options
  • Save benjchristensen/4671092 to your computer and use it in GitHub Desktop.
Save benjchristensen/4671092 to your computer and use it in GitHub Desktop.
Snippet of FuturesB.java Example of using Futures for nested calls showing how it blocks inefficiently.
ExecutorService executor = new ThreadPoolExecutor(4, 4, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());
// get f3 with dependent result from f1
Future<String> f1 = executor.submit(new CallToRemoteServiceA());
Future<String> f3 = executor.submit(new CallToRemoteServiceC(f1.get()));
/* The work below can not proceed until f1.get()
completes even though there is no dependency */
// also get f4/f5 after dependency f2 completes
Future<Integer> f2 = executor.submit(new CallToRemoteServiceB());
Future<Integer> f4 = executor.submit(new CallToRemoteServiceD(f2.get()));
Future<Integer> f5 = executor.submit(new CallToRemoteServiceE(f2.get()));
System.out.println(f3.get() + " => " + (f4.get() * f5.get()));
@benjchristensen
Copy link
Author

The full example with various implementations is at https://gist.github.com/4671081

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment