Shutdown ExecutorService when no task has been submitted for a given time

瘦欲@ 提交于 2019-12-11 10:25:17

问题


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.

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:

@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.

Any idea on how I could manage to do this?

Thanks in advance!

Regards,

Zim


回答1:


You could just use Executors.newCachedThreadPool(), whose doc says:

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.

This shuts down the threads, not the entire executor, but that should be fine if the executor isn't actually taking any resources.




回答2:


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:

return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
    60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());

The timeout here is 60 seconds. If you want to construct an executor with a fixed pool size that times out, you additionally have to set allowCoreThreadTimeOut(true):

ThreadPoolExecutor e = 
    new ThreadPoolExecutor(poolSize, poolSize,
        keepAliveTime, timeUnit, new LinkedBlockingQueue<Runnable>());
e.allowCoreThreadTimeOut(true);


来源:https://stackoverflow.com/questions/22693203/shutdown-executorservice-when-no-task-has-been-submitted-for-a-given-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!