ThreadPoolExecutor beforeExecute afterExecute Hooks

Subclass ThreadPoolExecutor to time every task: beforeExecute stamps the start, afterExecute reports elapsed time and whether the task ended with a throwable.

JavaResilience

Code

snippet
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TimedPool extends ThreadPoolExecutor {

    // beforeExecute 与 afterExecute 拿到的是同一个 Runnable 引用,可当键用
    private final Map<Runnable, Long> starts = new ConcurrentHashMap<>();

    TimedPool(int workers) {
        super(workers, workers, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
    }

    @Override
    protected void beforeExecute(Thread worker, Runnable task) {
        starts.put(task, System.nanoTime());
    }

    @Override
    protected void afterExecute(Runnable task, Throwable failure) {
        Long start = starts.remove(task);
        long elapsedMicros = start == null ? -1 : (System.nanoTime() - start) / 1_000;
        System.out.printf("%s done in %d us, failed=%b%n",
                Thread.currentThread().getName(), elapsedMicros, failure != null);
    }

    public static void main(String[] args) throws InterruptedException {
        TimedPool pool = new TimedPool(2);
        for (int batch = 1; batch <= 3; batch++) {
            int multiplier = batch;
            pool.execute(() -> {
                long sum = 0;
                for (int i = 0; i <= 100_000 * multiplier; i++) {
                    sum += i;
                }
                if (sum < 0) {
                    throw new IllegalStateException("impossible");
                }
            });
        }
        // execute() 直抛的任务会把 Throwable 交给 afterExecute 的 failure 参数
        pool.execute(() -> { throw new IllegalArgumentException("boom"); });
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
    }
}

Inside the snippet

Under the hood: the class TimedPool and the functions beforeExecute and afterExecute.

The file repeats itself only inside for (int batch = 1; batch <= 3; batch++). Invalid states are rejected up front: it throws IllegalStateException and IllegalArgumentException instead of continuing with bad data.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Putting it to use

The primary signature is protected void beforeExecute(Thread worker, Runnable task)

The core lines of the flow

pool.execute(() -> { throw new IllegalArgumentException("boom"); });
protected void beforeExecute(Thread worker, Runnable task) {
    starts.put(task, System.nanoTime());
}
throw new IllegalStateException("impossible");

Interactive Tools for This Topic

FAQ

Does the code validate its input?
`IllegalStateException` and `IllegalArgumentException` is raised at the guard, so invalid state never reaches the main logic.
How do you run ThreadPoolExecutor beforeExecute afterExecute Hooks?
It runs as-is — treat the file as the whole program and execute it.