2

I am creating thread pools like this:

ExecutorService workers = Executors.newCachedThreadPool();

Invoking each pool tasks like this:

workers.invokeAll(tasks);

And after completion shutting those down like this:

workers.shutdown();

I have about 4 thread pools that do different procedures and those thread pools are being created from a servlet class.

What I want to do is shutdown all threads in those thread pools.

What is the cleanest way to achieve this?

Thanks

RedEagle
  • 4,418
  • 9
  • 41
  • 64

1 Answers1

0

If all your worker tasks handle interrupts properly you could try to invoke:

workers.shutdownNow()

That call with typically send interrupts too all worker threads. However, proper interrupt handling is a bit implicit and the method documentation says that only a best effort attempt to stop the tasks is made. Hence, some JVM implementations might make a worse attempt than sending interrupts, why you might not want to trust this call.

You might want to look into other answers how to gracefully ensure proper shutdown of threads and implement such a solution for all your worker tasks, to guarantee proper shutdown. For example, in this answer, Jack explains the typical solution to have a volatile field that you can check in your workers. This field can be set from where you want to stop your tasks.

Community
  • 1
  • 1
K Erlandsson
  • 13,408
  • 6
  • 51
  • 67