Video in progress

Strong Junior 🧵 Concurrency

Why does an exception in a task sent with submit() not show up in the log?

submit() catches the exception and stores it inside the returned Future. If nobody calls get(), the error quietly disappears. execute(), on the other hand, passes the exception to the thread's UncaughtExceptionHandler.

📖 Answer

On prod it goes like this: a job that runs at night finishes "successfully", but there is no data. There is nothing in the log, because:

executor.submit(() -> {
    importFile(path);   // threw an NPE
});
// the Future was thrown away, and the exception went with it

The options:

// 1. Log inside the task itself
executor.submit(() -> {
    try {
        importFile(path);
    } catch (Exception e) {
        log.error("import yiqildi: {}", path, e);
        throw e;
    }
});

// 2. If you don't need a result: execute()
executor.execute(() -> importFile(path));  // the stack trace goes to stderr/the handler

// 3. Keep the Future and call get() later
Future<?> f = executor.submit(() -> importFile(path));
f.get();  // ExecutionException

CompletableFuture.runAsync is the same: the exception stays inside the future. Make it a habit to log at the end of the chain with .exceptionally(...) or .whenComplete(...).

For Spring @Async void methods there is a separate AsyncUncaughtExceptionHandler, and it is worth configuring.