Skip to content

Instantly share code, notes, and snippets.

@baybatu
Forked from kencharos/Comp.java
Last active January 11, 2023 06:01
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 baybatu/3dbcb91af02bc883633f932abcdba5e9 to your computer and use it in GitHub Desktop.
Save baybatu/3dbcb91af02bc883633f932abcdba5e9 to your computer and use it in GitHub Desktop.
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 CompleteableFutureWithExceptionHandling {
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