Skip to content

Instantly share code, notes, and snippets.

@sunels
Created December 2, 2018 19:46
Java 8 CompletableFuture parallel tasks and Timeout example
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by sunels on 02.12.2018.
*/
public class CompletableFutureTimeout {
public static void main (String[] args) {
int numOfParallelTasks = 10;
long startTime = System.currentTimeMillis ();
ExecutorService es = Executors.newFixedThreadPool (numOfParallelTasks);
List<CompletableFuture> futures = new ArrayList<> ();
CompletableFutureTimeout r = new CompletableFutureTimeout ();
for (long i = 0; i < numOfParallelTasks; i++) {
final long sleepDuration = i * 1000l;
CompletableFuture<String> future = CompletableFuture.supplyAsync (() -> r.doSomeSleep (sleepDuration), es);
futures.add (future);
}
System.out.println ("Duration here = " + (System.currentTimeMillis () - startTime));
try {
Thread.currentThread ().sleep (5000l);
} catch (InterruptedException e) {
}
List<Object> resultArray = new ArrayList<> ();
for (int i = 0; i < numOfParallelTasks; i++) {
Object result = futures.get (i).getNow (null);
resultArray.add (result);
}
es.shutdown ();
try {
if (!es.awaitTermination (1l, TimeUnit.NANOSECONDS)) {
es.shutdownNow ();
}
} catch (InterruptedException e) {
es.shutdownNow ();
}
System.out.println ("Collected Results = " + resultArray);
System.out.println ("Total Duration = " + (System.currentTimeMillis () - startTime));
}
public String doSomeSleep (long sleep) {
String result;
try {
Thread.sleep (sleep);
System.out.println (Thread.currentThread ().getName () + " - - > will sleep for secs :" + sleep);
result = sleep + "";
} catch (Exception e) {
result = e.getMessage ();
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment