javajava-21virtual-threadsproject-loom

Is it necessary to shutdown the executor returned by Executors.newVirtualThreadPerTaskExecutor()?


Project loom introduced a virtual thread executor service Executors.newVirtualThreadPerTaskExecutor() which creates a new Virtual Thread (VT) every time we submit a task.

I have a couple of questions regarding it:

  1. Java is not pooling anything and is creating a new VT for each task. is it necessary to shutdown the virtual thread pool? If so, what does it do internally?
  2. if the shutdown is required, then how do I clean VTs that are created using thread factory threadFactory.newThread()

I have gone through Virtual Thread JEP, and it doesn't seem to mention anything about this topic.


Solution

  • You need to shut down if you want to be sure the executor service doesn't accept new tasks, and if you want to be able to await completion of all previously submitted tasks.

    And given virtual threads are always daemon threads, awaiting termination is required if you want to be certain your tasks have all finished before you exit the application.

    So, if you don't care if the tasks submitted to a virtual-thread executor service have completed before JVM exit, then you don't need to shut it down, but otherwise you really do need to shut down and await termination.

    There is nothing special to do to clean up virtual threads. Once they end, they will be gone.