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
Release: 2024-11-28 04:25:13
Original
427 people have browsed it

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">private final long timeout;
private final TimeUnit timeoutUnit;

// ... (rest of the implementation)
Copy after login

}

Usage

To utilize this executor service, simply create an instance, specifying the desired timeout:

TimeoutThreadPoolExecutor executor = new TimeoutThreadPoolExecutor(..., timeout, TimeUnit.MILLISECONDS);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template