实现说明
全部实现位于 TimedPool和函数 beforeExecute、afterExecute。
在这里做循环的是 for (int batch = 1; batch <= 3; batch++)。IllegalStateException、IllegalArgumentException 是守卫的信号——在分支处抛出,任何半成品工作之前。
常见问题
这段代码会校验输入吗?
守卫处(入口)会抛出 IllegalStateException、IllegalArgumentException,非法状态到不了主逻辑。
「ThreadPoolExecutor 任务生命周期钩子」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
入口签名:protected void beforeExecute(Thread worker, Runnable task)
核心语句
pool.execute(() -> { throw new IllegalArgumentException("boom"); });
protected void beforeExecute(Thread worker, Runnable task) {
starts.put(task, System.nanoTime());
}
throw new IllegalStateException("impossible");
代码示例
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);
}
}