java线程池任务超时问题
java thread pool task timeout issue
我有一个线程池:
ThreadPoolExecutor pool = new ThreadPoolExecutor(cores, 50, 30L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3000));
然后我运行:
try {
pool.execute(() ->
{
//Very very long task, fetching from an external URL
});
}catch(Exception e){
e.printStackTrace();
}
我从来没有遇到异常,这段代码等待几分钟。
我应该怎么做才能让它在 30 秒内取消?
根据文档,第 3 个参数 keepAlive 没有指定线程池中特定任务的等待时间,但应该从池中释放空闲线程的时间。
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
对于您想要的行为,您应该将您的任务包装在 FutureTask 中,然后将未来的任务提交给线程池。在未来的任务中,您可以调用 get(timeout, timeunit)
FutureTask<T> task = new FutureTask<T>(c);
pool.execute(task);
return task.get(timeout, timeUnit);
您指定的 30 秒是执行程序空闲线程的 keepAliveTime
。这是当前未处理任务的多余线程将保持活动状态的持续时间。这里多余的线程被定义为除了每个内核一个线程之外创建的线程,您的 ThreadPoolExecutor
将保持活动状态,具体取决于您指定的 corePoolSize
。
为了提交一个超时的任务,你可以只在你的ThreadPoolExecutor
中提交任务,获取返回的Future
并使用它的超时get(long timeout, TimeUnit unit)
方法:
Future<Result> future = pool.execute(yourTask);
Result result = future.get(30, TimeUnit.SECONDS);
你也可以看看这个相关问题:ExecutorService that interrupts tasks after a timeout
我有一个线程池:
ThreadPoolExecutor pool = new ThreadPoolExecutor(cores, 50, 30L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3000));
然后我运行:
try {
pool.execute(() ->
{
//Very very long task, fetching from an external URL
});
}catch(Exception e){
e.printStackTrace();
}
我从来没有遇到异常,这段代码等待几分钟。 我应该怎么做才能让它在 30 秒内取消?
根据文档,第 3 个参数 keepAlive 没有指定线程池中特定任务的等待时间,但应该从池中释放空闲线程的时间。
* @param keepAliveTime when the number of threads is greater than * the core, this is the maximum time that excess idle threads * will wait for new tasks before terminating.
对于您想要的行为,您应该将您的任务包装在 FutureTask 中,然后将未来的任务提交给线程池。在未来的任务中,您可以调用 get(timeout, timeunit)
FutureTask<T> task = new FutureTask<T>(c);
pool.execute(task);
return task.get(timeout, timeUnit);
您指定的 30 秒是执行程序空闲线程的 keepAliveTime
。这是当前未处理任务的多余线程将保持活动状态的持续时间。这里多余的线程被定义为除了每个内核一个线程之外创建的线程,您的 ThreadPoolExecutor
将保持活动状态,具体取决于您指定的 corePoolSize
。
为了提交一个超时的任务,你可以只在你的ThreadPoolExecutor
中提交任务,获取返回的Future
并使用它的超时get(long timeout, TimeUnit unit)
方法:
Future<Result> future = pool.execute(yourTask);
Result result = future.get(30, TimeUnit.SECONDS);
你也可以看看这个相关问题:ExecutorService that interrupts tasks after a timeout