I am using an ExecutorService for a connection task as below:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<ApplicationConnection> future = (Future<ApplicationConnection>) executor.submit(new ConnectThread(crf, connoptions));
connection = future.get(300000, TimeUnit.SECONDS);
executor.shutdownNow();
The call() method calls a .connect() method (proprietary API). This connect method spawns various threadpools etc. My concern is that if the future times out and kills the executor, will the threads that may have already spawned by calling the .connect() method in the future also end? I know that killing a thread will also kill any child threads but does this follow the same logic?
You are right in your assumption, if the
Futuretimes out, some hanging threads will remain. Even worse,shutdownNow()will not even shutdown your pool thread (not to mention proprietary API threads). It merely stops accepting new jobs.ExecutorServicethread pool will terminate all threads once all running tasks finish.What you can do is to try canceling the future and interrupting it. First handle
InterruptedExceptioninside your future:Now simply run:
However your proprietary API might not handle
InterruptedException(it will not rethrow it fromconnect(), moreover you might not have access to anycleanUp()method.In these circumstances just… forget about it. That
Futurewill eventually terminate and clean up after itself, ignoring the fact that you no longer wait for it. Of course this might lead to various scalability issues.BTW if the only thing you want to achieve is limiting the maximum time given method runs, consider
TimeLimiterfrom guava.