Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

FuturesA.java Simple example of using Futures.

View FuturesA.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
public class FuturesA {
 
public static void run() throws Exception {
ExecutorService executor = new ThreadPoolExecutor(4, 4, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());
 
Future<String> f1 = executor.submit(new CallToRemoteServiceA());
Future<String> f2 = executor.submit(new CallToRemoteServiceB());
 
System.out.println(f1.get() + " - " + f2.get());
}
 
public static void main(String args[]) {
try {
run();
} catch (Exception e) {
e.printStackTrace();
}
}
 
private static final class CallToRemoteServiceA implements Callable<String> {
@Override
public String call() throws Exception {
// simulate fetching data from remote service
Thread.sleep(100);
return "responseA";
}
}
 
private static final class CallToRemoteServiceB implements Callable<String> {
@Override
public String call() throws Exception {
// simulate fetching data from remote service
Thread.sleep(40);
return "responseB";
}
}
}

Will you consider add those after the io?

    executor.shutdown();
    executor.awaitTermination(100, TimeUnit.MILLISECONDS);

The expected output is that System.out.println(f1.get() + " - " + f2.get());

will take 140 ms to return?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.