Skip to content

Instantly share code, notes, and snippets.

@kencharos
Created February 17, 2017 10:35
Show Gist options
  • Save kencharos/14f091e91202e14e846090299c5d9a6e to your computer and use it in GitHub Desktop.
Save kencharos/14f091e91202e14e846090299c5d9a6e 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 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