← 中文资源

简体中文版本

Java Executor 批量超时与取消

用 invokeAll 在固定线程池上执行一批任务并设置总截止时间,区分完成、取消与失败,最后关闭线程池。

阅读英文原文

功能说明

BatchRunner 创建包含三个线程的固定线程池,提交五个分别睡眠 150 到 750 毫秒的 Callable。invokeAll 的总超时设为 500 毫秒,返回后逐个检查 Future:已完成的读取结果,被取消的单独计数,执行异常则打印 cause。示例预期前三个任务完成,后两个在截止时间到达时被取消,从而展示批量任务的部分成功语义。

关键代码

invokeAll(tasks, timeout, unit) 会阻塞到全部任务完成或超时;超时后未完成的任务会被取消,返回列表与输入顺序一致。isCancelled 必须在 get 之前判断,否则 get 会抛 CancellationException。ExecutionException 包装任务内部异常,应读取 getCause。finally 中调用 shutdownNow 并 awaitTermination,确保线程池不会阻止 JVM 退出。任务 id 复制到 final 局部变量,满足 lambda 捕获要求。

使用注意

invokeAll 的超时是整批共享的,不是每个任务各自 500 毫秒;如果需要单任务预算,应在任务内部使用带超时的 API。shutdownNow 会中断正在运行的任务,任务必须响应中断才有意义。示例中的 Thread.sleep 会抛 InterruptedException,Callable 允许受检异常,因此无需额外包装。线程池大小要结合 CPU 与阻塞比例设置。生产代码还应记录哪些任务被取消,并提供重试或补偿。

验证方式

运行 main,预期输出 succeeded=3 cancelled=2,前三个任务按完成顺序打印结果。把超时改为 1 秒可让五个任务全部完成;改为 100 毫秒则只可能完成第一个任务。若在某个任务中抛 RuntimeException,可观察到该 Future 进入 ExecutionException 分支,而其他任务继续执行。

代码示例

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class BatchRunner {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        List<Callable<String>> tasks = new ArrayList<>();
        for (int id = 1; id <= 5; id++) {
            final int taskId = id;
            tasks.add(() -> {
                Thread.sleep(taskId * 150L);
                return "task-" + taskId;
            });
        }

        try {
            List<Future<String>> futures = pool.invokeAll(tasks, 500, TimeUnit.MILLISECONDS);
            int succeeded = 0;
            int cancelled = 0;

            for (int index = 0; index < futures.size(); index++) {
                Future<String> future = futures.get(index);
                if (future.isCancelled()) {
                    cancelled++;
                    System.out.println("task " + (index + 1) + " cancelled");
                    continue;
                }
                try {
                    System.out.println("result: " + future.get());
                    succeeded++;
                } catch (ExecutionException error) {
                    System.out.println("task " + (index + 1) + " failed: " + error.getCause());
                }
            }
            System.out.println("succeeded=" + succeeded + " cancelled=" + cancelled);
        } finally {
            pool.shutdownNow();
            if (!pool.awaitTermination(2, TimeUnit.SECONDS)) {
                System.err.println("pool did not terminate in time");
            }
        }
    }
}