2

I'm new to java executor stuff.

I'm using Java's ExecutorService to launch several threads to process data.

Executor executor = Executors.newFixedThreadPool(poolSize);

for(int i=0; i< 5;i++) executor.execute(new MyRunnable(i));

once the threads don't find data, they gracefully terminate.

My question is what happens to the Executor when all the threads terminate, is it still running its master thread ? or it will terminate itself and whole application will finish gracefully?

in case executor thread still runs, how can I let it terminate once all its child threads are done (poolSize number of threads).

4 Answers 4

3

Executor will keep running with the underlying thread pool. You can still execute or submit a new task. It is recommended to shutdown Executor service call ExecutorService.html#shutdown() which attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

You can also use ExecutorService.html#shutdownNow() which stops all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. It is useful when you need immediate shutdown.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Quoi. anyway can I send some signal from MyRunnable thread class saying that lets shutdownNow() executor service?
3

1) threads in a fixed thread pool executor never terminate once started

2) there is no master thread in thread pool executor

4 Comments

ok. anyway to stop the pool once all the worker threads are done processing?
executor.shutdown() otherwise your app will never end
agree. that means I need to pass the executor object to MyRunnable and then shutdown from there. hopefully that should be right place to do.
Are there any conditions where the program does terminate? I have cases where it terminates, and cases where it doesn't.
2

you can think of it that way:

shutdown() will just tell the executor service that it can't accept new tasks, but the already submitted tasks continue to run

shutdownNow() will do the same AND will try to cancel the already submitted tasks by interrupting the relevant threads. Note that if your tasks ignore the interruption, shutdownNow will behave exactly the same way as shutdown.

Comments

1

Use shutdown method to gracefully shutdown from interface ExecuterService, as Quoi suggested it still runs even if threads are done. You can use submit anytime after that for new work. Other utility methods are here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.