Search code examples
javamultithreadingexecutorservicethreadpoolexecutorexecutor

How to reuse an executor objects after threads shutdown


I have a Java 7 program which parallel processes chunks of data and currently I use the executor service API to create the threads:

pool = Executors.newFixedThreadPool(size > 0 ? size : THREAD_MAX);

And then I wait for all the threads to finish up:

    try {
        pool.shutdown();
        // TODO 60 seconds sufficient to process a route?
        pool.awaitTermination(60L, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
        pool.shutdownNow(); // TODO consider rerunning handleHashes!
    } finally {
        release();
    }

But once the termination happens, I need to re-instantiate the executor. I'd much rather reuse already created threads after the previous chunk of data has been processed. This would make profiling much easier for me.

After the .shutdown() how can I reuse the Executor object and the threads inside it instead of re-instantiating?

Perhaps, are there 3rd party Executor APIs that have this feature?


Solution

  • Maybe you could restructure your program so the processing threads don't shut down. Your parent thread gives child threads data to process. They process it and wait for more data. Don't kill the threads or shut down the pool between data processes.