Skip to content

Instantly share code, notes, and snippets.

@mping
Last active March 27, 2018 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mping/8ece6ce48a7d403b81ad4e19b350abad to your computer and use it in GitHub Desktop.
Save mping/8ece6ce48a7d403b81ad4e19b350abad to your computer and use it in GitHub Desktop.
CompletableFuture gotcha
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureWUT {
static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
CompletableFuture<Object> firstProcess = CompletableFuture.supplyAsync(() -> {
sleep(2000L);
System.out.println("first process");
return "1";
});
CompletableFuture<Object> secondProcess = firstProcess.thenApplyAsync(v -> {
sleep(3000);
System.out.println("second process");
return "2";
});
CompletableFuture<Void> completableFuture = CompletableFuture.allOf(firstProcess, secondProcess);
completableFuture.thenApplyAsync(v -> {
System.out.println("allOf completed");
return "3";
});
try {
completableFuture.get(100, TimeUnit.MILLISECONDS);
} catch (Exception e) {
System.out.println("Timeout!");
}
Thread.sleep(10000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment