java 超时中断_JavaExecutorService在超时后中断任务

我正在寻找可以提供超时的ExecutorService实现。如果提交到ExecutorService的任务花费的时间超过了超时时间,则这些任务将被中断。实现这样的野兽并不是一个困难的任务,但是我想知道是否有人知道现有的实现。

这是我根据以下一些讨论得出的。任何意见?

import java.util.List;

import java.util.concurrent.*;

public class TimeoutThreadPoolExecutor extends ThreadPoolExecutor {

private final long timeout;

private final TimeUnit timeoutUnit;

private final ScheduledExecutorService timeoutExecutor = Executors.newSingleThreadScheduledExecutor();

private final ConcurrentMap runningTasks = new ConcurrentHashMap();

public TimeoutThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, long timeout, TimeUnit timeoutUnit) {

super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);

this.timeout = timeout;

this.timeoutUnit = timeoutUnit;

}

public TimeoutThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, long timeout, TimeUnit timeoutUnit) {

super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);

this.timeout = timeout;

this.timeoutUnit = timeoutUnit;

}

public TimeoutThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, RejectedExecutionHandler handler, long timeout, TimeUnit timeoutUnit) {

super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);

this.timeout = timeout;

this.timeoutUnit = timeoutUnit;

}

public TimeoutThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler, long timeout, TimeUnit timeoutUnit) {

super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);

this.timeout = timeout;

this.timeoutUnit = timeoutUnit;

}

@Override

public void shutdown() {

timeoutExecutor.shutdown();

super.shutdown();

}

@Override

public List shutdownNow() {

timeoutExecutor.shutdownNow();

return super.shutdownNow();

}

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

}

}

@Override

protected void afterExecute(Runnable r, Throwable t) {

ScheduledFuture timeoutTask = runningTasks.remove(r);

if(timeoutTask != null) {

timeoutTask.cancel(false);

}

}

class TimeoutTask implements Runnable {

private final Thread thread;

public TimeoutTask(Thread thread) {

this.thread = thread;

}

@Override

public void run() {

thread.interrupt();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值