[英]Shutdown ExecutorService when no task has been submitted for a given time
I'm using an ExecutorService
to call a service which basically connects to an application (local or remote via SSH), and allows to send commands to it and get its output.我正在使用
ExecutorService
调用一个服务,该服务基本上连接到一个应用程序(通过 SSH 本地或远程),并允许向它发送命令并获取它的输出。
So, the Thread
created by the ExecutorService
is waiting for user input, and this input is then processed as a task through an implementation of the call method, which returns the output and looks like this:所以,
ExecutorService
创建的Thread
正在等待用户输入,然后通过 call 方法的实现将这个输入作为任务处理,它返回输出,如下所示:
@Override
public String call() throws Exception {
write(command);
return readResult();
}
I would like to stop the Thread
(shutdown the ExecutorService
) when no task has been called for a given time, but I can't find how to do it... Future.get
or ExecutorService.invoke[All|Any]
can handle a timeout, but only regarding tasks it calls.当在给定时间内没有调用任何任务时,我想停止
Thread
(关闭ExecutorService
),但我找不到如何去做... Future.get
或ExecutorService.invoke[All|Any]
可以处理超时,但仅限于它调用的任务。
Any idea on how I could manage to do this?关于我如何做到这一点的任何想法?
You could just use Executors.newCachedThreadPool()
, whose doc says:您可以只使用
Executors.newCachedThreadPool()
,其文档说:
Threads that have not been used for sixty seconds are terminated and removed from the cache.
六十秒内未使用的线程将被终止并从缓存中删除。 Thus, a pool that remains idle for long enough will not consume any resources.
因此,保持空闲足够长时间的池不会消耗任何资源。 Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.
请注意,可以使用 ThreadPoolExecutor 构造函数创建具有相似属性但细节不同(例如超时参数)的池。
This shuts down the threads, not the entire executor, but that should be fine if the executor isn't actually taking any resources.这会关闭线程,而不是整个执行程序,但如果执行程序实际上没有占用任何资源,那应该没问题。
You may want to have a look at the implementation of the Executors
class: The executors created, for example, with newCachedThreadPool()
already have a timeout:您可能想看看
Executors
类的实现: 例如,使用newCachedThreadPool()
创建的执行器已经有超时:
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
The timeout here is 60 seconds.这里的超时时间是 60 秒。 If you want to construct an executor with a fixed pool size that times out, you additionally have to set
allowCoreThreadTimeOut(true)
:如果要构造一个具有固定池大小的超时执行器,则还必须设置
allowCoreThreadTimeOut(true)
:
ThreadPoolExecutor e =
new ThreadPoolExecutor(poolSize, poolSize,
keepAliveTime, timeUnit, new LinkedBlockingQueue<Runnable>());
e.allowCoreThreadTimeOut(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.