I'm trying to catch uncaught exceptions on futures like this CompletableFuture.runAsync(() -> {throw new RuntimeException();});
My goal is to make these exceptions not silent when developpers forget to handle them.
- Calling get()orjoin()and try/catch exceptions is not an option because it is not global to all usages of future in the code base
- Adding .exceptionnaly(...)orhandle(...)is not an option for the same reason. It's exactly what I'm trying to prevent
Here's what I do (which doesn't work)
public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        System.setProperty("java.util.concurrent.ForkJoinPool.common.exceptionHandler", UncaughtExceptionHandler.class.getName());
        CompletableFuture.runAsync(() -> {
            System.out.println("async");
            throw new RuntimeException();
        });
        System.out.println("Done");
        Thread.sleep(1000);
    }
    static class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println("Uncaught!");
        }
    }
}
It prints
Done
Async
What am I missing ?
EDIT
I tried this but still not working
public class Main {
    public static void main(String[] args) throws InterruptedException {
        CompletableFuture.runAsync(() -> {
                    System.out.println("Async");
                    throw new RuntimeException();
                },
                new ForkJoinPool(
                        Runtime.getRuntime().availableProcessors(),
                        ForkJoinPool.defaultForkJoinWorkerThreadFactory,
                        (t, e) -> System.out.println("Uncaught!"), // UncaughtExceptionHandler
                        false));
        System.out.println("Done");
        Thread.sleep(1000);
    }
}
It seems that the ForkJoinPool ignores its UncaughtExceptionHandler, and even its ForkJoinWorkerThreadFactory because I tried to define that as well
 
     
    