FuturesA.java

Simple example of using Futures. (original) (raw)

FuturesA.java Simple example of using Futures.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters

[ Show hidden characters]({{ revealButtonHref }})

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";
}
}
}