Home > Java > javaTutorial > How to Set a Timeout for a Thread in Java Using ExecutorService?

How to Set a Timeout for a Thread in Java Using ExecutorService?

Barbara Streisand
Release: 2024-12-16 12:55:17
Original
607 people have browsed it

How to Set a Timeout for a Thread in Java Using ExecutorService?

How to Set a Timeout for a Thread

As raised in the initial inquiry, there is a concern about how to restrict a thread's execution time. The goal is to handle situations where a thread might enter an infinite loop, resulting in the parent thread waiting indefinitely.

One solution discussed involves using a TimerTask within the Thread's run() method. However, a more efficient approach is to leverage the ExecutorService class. This provides a convenient mechanism for setting a timeout on a thread.

An example implementation using ExecutorService can be illustrated as follows:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class TimeoutTest {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new Task());

        try {
            System.out.println("Started..");
            System.out.println(future.get(3, TimeUnit.SECONDS));
            System.out.println("Finished!");
        } catch (TimeoutException e) {
            future.cancel(true);
            System.out.println("Terminated!");
        }

        executor.shutdownNow();
    }
}

class Task implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(4000); // Simulate a long-running task that takes 4 seconds
        return "Ready!";
    }
}
Copy after login

In this example, the Task class encapsulates the long-running task. The ExecutorService.submit() method is used to submit this task for execution. The Future object returned by submit() provides a mechanism for retrieving the result of the task.

The Future.get() method is called with a timeout argument of 3 seconds. If the task finishes within this time frame, the result is returned. However, if the task takes longer than 3 seconds, a TimeoutException is thrown. In the catch block, the task is canceled and the "Terminated!" message is printed.

Additionally, it's important to note that in the long-running task, a check should be incorporated to handle interruptions, preventing the task from running indefinitely. This check can be implemented using Thread.interrupted().

The above is the detailed content of How to Set a Timeout for a Thread in Java Using ExecutorService?. 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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template