Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CompletableFuture sample(with simple error handling)
package com.example;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Comp {
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(3);
CompletableFuture.allOf(
CompletableFuture.runAsync(() -> callService("line1"),es),
CompletableFuture.runAsync(() -> callService("line2-error"),es)
.exceptionally(e -> errorHandle(e)) // add error handling.
//...
).join();
System.out.println("end");
es.shutdown();
}
private static void callService(String content){
System.out.println("call " + content + " in " + Thread.currentThread());
if (content.contains("error")) {
throw new RuntimeException("fake error");
}
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static Void errorHandle(Throwable e){
if (e != null) {
System.out.println("error occured. " + e.getMessage());
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment