带超时的可中断ExecutorService
并行执行耗时任务时,控制执行超时至关重要,防止任务无限期占用资源。本文探讨了提供此类超时功能的 ExecutorServices 的现有实现。
一种解决方案是定制的 ExecutorService,由以下贡献者设计,用于监视任务执行并中断任何超过预定义超时的情况:
import java.util.List; import java.util.concurrent.*; public class TimeoutThreadPoolExecutor extends ThreadPoolExecutor { // Timeout configuration private final long timeout; private final TimeUnit timeoutUnit; // Task and timeout scheduling private final ScheduledExecutorService timeoutExecutor = Executors.newSingleThreadScheduledExecutor(); private final ConcurrentMap<Runnable, ScheduledFuture> runningTasks = new ConcurrentHashMap<>(); // Initialize with timeout and scheduling options public TimeoutThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, long timeout, TimeUnit timeoutUnit) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); this.timeout = timeout; this.timeoutUnit = timeoutUnit; } // ExecutorService lifecycle management @Override public void shutdown() { timeoutExecutor.shutdown(); super.shutdown(); } @Override public List<Runnable> shutdownNow() { timeoutExecutor.shutdownNow(); return super.shutdownNow(); } // Monitor task execution and initiate timeouts @Override protected void beforeExecute(Thread t, Runnable r) { if (timeout > 0) { final ScheduledFuture<?> scheduled = timeoutExecutor.schedule(new TimeoutTask(t), timeout, timeoutUnit); runningTasks.put(r, scheduled); } } // Handle tasks after completion and cancel timeouts @Override protected void afterExecute(Runnable r, Throwable t) { ScheduledFuture timeoutTask = runningTasks.remove(r); if (timeoutTask != null) { timeoutTask.cancel(false); } } // Task responsible for interrupting long-running tasks class TimeoutTask implements Runnable { private final Thread thread; public TimeoutTask(Thread thread) { this.thread = thread; } @Override public void run() { thread.interrupt(); } } }
此自定义实现提供了一种方便有效的方法来监视任务执行和强制超时,确保多线程中的任务行为可预测环境。
以上是如何在 Java 中实现带超时的可中断 ExecutorService?的详细内容。更多信息请关注PHP中文网其他相关文章!