Home >Java >javaTutorial >How Can I Create an ExecutorService That Interrupts Tasks After a Timeout?

How Can I Create an ExecutorService That Interrupts Tasks After a Timeout?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-28 04:25:13393browse

How Can I Create an ExecutorService That Interrupts Tasks After a Timeout?

Timeout Executor Service

Overview

In this context, we are interested in an ExecutorService implementation capable of interrupting tasks that exceed a predefined timeout.

Existing Implementations

One such implementation is TimeoutThreadPoolExecutor, which provides a mechanism to specify a timeout duration for submitted tasks.

Implementation Details

<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)

}

Usage

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.

Alternative Approach

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn