Home >Java >javaTutorial >How Can I Implement an Interruptible ExecutorService with Timeouts in Java?
Interruptible ExecutorService with Timeouts
When executing time-consuming tasks in parallel, it's essential to control execution timeouts to prevent tasks from indefinitely occupying resources. This article explores existing implementations of ExecutorServices that provide such timeout capabilities.
One solution is a customized ExecutorService, devised by contributors below, that monitors task execution and interrupts any exceeding a predefined timeout:
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(); } } }
This custom implementation provides a convenient and efficient way to monitor task execution and enforce timeouts, ensuring predictable task behavior in multithreaded environments.
The above is the detailed content of How Can I Implement an Interruptible ExecutorService with Timeouts in Java?. For more information, please follow other related articles on the PHP Chinese website!