Home >Java >javaTutorial >How Can I Create an ExecutorService That Interrupts Tasks After a Timeout?
In this context, we are interested in an ExecutorService implementation capable of interrupting tasks that exceed a predefined timeout.
One such implementation is TimeoutThreadPoolExecutor, which provides a mechanism to specify a timeout duration for submitted tasks.
<br>import java.util.List;<br>import java.util.concurrent.*;</p> <p>public class TimeoutThreadPoolExecutor extends ThreadPoolExecutor {</p> <pre class="brush:php;toolbar:false">private final long timeout; private final TimeUnit timeoutUnit; // ... (rest of the implementation)
}
To utilize this executor service, simply create an instance, specifying the desired timeout:
TimeoutThreadPoolExecutor executor = new TimeoutThreadPoolExecutor(..., timeout, TimeUnit.MILLISECONDS);
Then, submit your tasks to the executor as usual. Tasks that exceed the specified timeout will be interrupted.
Alternatively, you can employ a ScheduledExecutorService:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); Future<?> handler = executor.submit(new Callable() { /* ... */ }); executor.schedule(() -> handler.cancel(true), 10000, TimeUnit.MILLISECONDS);
This strategy ensures that the task is interrupted after 10 seconds.
The above is the detailed content of How Can I Create an ExecutorService That Interrupts Tasks After a Timeout?. For more information, please follow other related articles on the PHP Chinese website!