Java Code Examples: Concurrency

Get Task Results Concurrently

ExecutorService

the order to get future results is the tasks order. If the later task executes faster than the earlier task, you still need to wait for the earlier task to complete.

public static void executorService() {
int threadNum = 10;
ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
long start = System.currentTimeMillis();
List<Future> futureList = new ArrayList<>(threadNum);
for (int i = 0; i < threadNum; i++) {
Future<String> future = executorService.submit(() -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
int randomNumber = random.nextInt(10);
System.out.println(Thread.currentThread().getName() + ": " + randomNumber);
Thread.sleep(1000 * randomNumber);
return Thread.currentThread().getName();
});
futureList.add(future);
}
for (int i = 0; i < threadNum; i++) {
try {
System.out.println(futureList.get(i).get());
System.out.println("elapsed time: " + (System.currentTimeMillis() - start) + "ms");
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("elapsed time: " + (System.currentTimeMillis() - start) + "ms");
executorService.shutdown();
}

ExecutorCompletionService

the order to get future results is the execution time of tasks from short to long.

public static void executorCompletionService() {
int threadNum = 10;
ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
ExecutorCompletionService completionService =
new ExecutorCompletionService<>(executorService);
long start = System.currentTimeMillis();
for (int i = 0; i < threadNum; i++) {
completionService.submit(() -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
int randomNumber = random.nextInt(10);
System.out.println(Thread.currentThread().getName() + ": " + randomNumber);
Thread.sleep(1000 * randomNumber);
return Thread.currentThread().getName();
});
}
for (int i = 0; i < threadNum; i++) {
try {
System.out.println(completionService.take().get());
System.out.println("elapsed time: " + (System.currentTimeMillis() - start) + "ms");
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("elapsed time: " + (System.currentTimeMillis() - start) + "ms");
executorService.shutdown();
}