-
-
Save baybatu/3dbcb91af02bc883633f932abcdba5e9 to your computer and use it in GitHub Desktop.
CompletableFuture sample (with simple error handling)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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