首页 > Java > java教程 > 如何在 Java 中实现带超时的可中断 ExecutorService?

如何在 Java 中实现带超时的可中断 ExecutorService?

Mary-Kate Olsen
发布: 2024-12-06 14:34:11
原创
273 人浏览过

How Can I Implement an Interruptible ExecutorService with Timeouts in Java?

带超时的可中断ExecutorService

并行执行耗时任务时,控制执行超时至关重要,防止任务无限期占用资源。本文探讨了提供此类超时功能的 ExecutorServices 的现有实现。

一种解决方案是定制的 ExecutorService,由以下贡献者设计,用于监视任务执行并中断任何超过预定义超时的情况:

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();
        }
    }
}
登录后复制

此自定义实现提供了一种方便有效的方法来监视任务执行和强制超时,确保多线程中的任务行为可预测环境。

以上是如何在 Java 中实现带超时的可中断 ExecutorService?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板