帶超時的可中斷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中文網其他相關文章!