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