Search code examples
javamultithreadingthreadpoolexecutor

Scope of Executor Service in java?


Recently I've been using VM template to write some contents to .vm file and then store the contents of vm file as .txt file in my computer. At first, I've been creating seperate thread for each file creation process which is not good due to large no of thread creations within short amount of time. So I thought to go with Thread Pool

Consider the following method

public void runHugeNoOfShortTimeTasks() {
    ExecutorService service = Executors.newFixedThreadPool(100);
    for(int i=0;i<10000;i++){
        service.submit(runnableWriteToVMAndConvertToTXTFile());   // Each process would take around 1-3 seconds
    }
}

Now consider it takes 0.5 seconds to complete the for loop. If the loop has finished, the process will exit the runHugeNoOfShortTimeTasks() method. But the scope of ExecutorService is within that method, so what will happen to Threads in queue and the ones which are processing? Does the Executor service will be garbage collected once the process exits the runHugeNoOfShortTimeTasks() method?

Another thing is that what will happen to that fixed thread pool of 100 once all the threads in queue are completed (if it's not going to be garbage collected). Does it'll be always sit in my memory waiting for threads or will it be destoryed once all threads are completed?

Maybe I'm completely wrong with my way of understanding, clarify me if I'm wrong..


Solution

  • No, the ExecutorService will not be garbage collected once the thread exits runHugeNoOfShortTimeTasks(). This is because the threads that the ExecutorService is using to run the tasks still can "reach" the Object. Once all tasks are finished, the threads will exit out and die, and at that point the ExecutorService will be eligible for garbage collection