Skip to content

Instantly share code, notes, and snippets.

module moduleA {
requires moduleB;
export packageC;
}
private static void exceptionUsingHandle() {
Integer age = -1;
CompletableFuture<String> exceptionFuture = CompletableFuture.supplyAsync(() -> {
if (age < 0) {
throw new IllegalArgumentException("Age can not be negative");
}
if (age > 18) {
return "Adult";
} else {
return "Child";
private static void exception() {
Integer age = -1;
CompletableFuture<String> exceptionFuture = CompletableFuture.supplyAsync(() -> {
if (age < 0) {
throw new IllegalArgumentException("Age can not be negative");
}
if (age > 18) {
return "Adult";
} else {
return "Child";
private static void chainOfThenApply() {
CompletableFuture.supplyAsync(() -> {
// Code which might throw an exception
return "Some result";
}).thenApply(result -> {
return "processed result";
}).thenApply(result -> {
return "result after further processing";
}).thenAccept(result -> {
// do something with the final result
private static void anyOf() throws Exception {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Result of Future 1";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
combinedFuture.thenApply(v ->
Stream.of(completableFuture1, completableFuture2, completableFuture3).
map(CompletableFuture::join).
collect(Collectors.toList()));
String combined = Stream.of(completableFuture1, completableFuture2, completableFuture3)
.map(CompletableFuture::join)
.collect(Collectors.joining(" "));
System.out.println(combined); // Hello Knolders! Its allOf
combinedFuture.get();
assertTrue(future1.isDone());
assertTrue(future2.isDone());
assertTrue(future3.isDone());
private static void allOf() {
CompletableFuture<String> completableFuture1
= CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> completableFuture2
= CompletableFuture.supplyAsync(() -> "Knolders!");
CompletableFuture<String> completableFuture3
= CompletableFuture.supplyAsync(() -> "Its allOf");
CompletableFuture<Void> combinedFuture
= CompletableFuture.allOf(completableFuture1, completableFuture2, completableFuture3);
private static void thenAcceptBoth() {
CompletableFuture<Void> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> " Knolders! Its thenAcceptBoth"),
(value1, value2) -> System.out.println(value1 + value2)); // Hello Knolders! Its thenAcceptBoth
}
private static void thenCombine() {
CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "Hello")
.thenCombine(CompletableFuture.supplyAsync(
() -> " Knolders! Its thenCombine"), (value1, value2) -> value1 + value2);
completableFuture.thenAccept(System.out::println); // Hello Knolders! Its thenCombine
}