I am using ExecutorService
in Java web server application for executing some computational tasks in parallel style and then calling shutdown()
with awaitTermination()
to wait for all tasks to be done. Whole computation can sometimes take dozens of minutes.
The thing is awaitTermination()
method blocks the main thread until timeout elapsed (or interrupted) but I just want to start the tasks and immediatedly respond to client and after competition of all tasks shutdown the service (following conventions to always close the thread pool).
So my question, is there a way how I can be notified when all tasks are done so I could call the shutdown()
method? Listener or something..
Thanks!
You are trying to solve a problem that doesn’t exist. Consider the documentation of
ExecutorService.shutdown()
:In other words, just calling
shutdown()
does already everything you wantThe only obstacle is that you are calling
awaitTermination
despite the fact that you don’t want to wait, which has a trivial solution: don’t callawaitTermination
.The confusion arises because in your question you are asking “how I can be notified when all tasks are done so I could call the
shutdown()
method” but that is in contradiction to what you are actually doing in the code. You are callingawaitTermination
aftershutDown
so you are not waiting in order to initiate the shutdown, but initiating theshutdown
first and waiting for its completion then, which is the purpose ofawaitTermination
, waiting for the completion of the shutdown.To put it in one sentence, just call
shutDown
after submission in order to shutdown the service after completion of all submitted jobs and don’t callawaitTermination
unless you really want to wait for the termination.