Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top