Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Thread factory = Thread.builder().virtual().factory()
try (ExecutorService executor = Executors.newUnboundedExecutor(factory)) {
    executor.schedule(task1);
    executor.schedule(task2);
}

...

This structure lends itself to nesting or even a tree of tasks:

try (ExecutorService executor = Executors.newUnboundedExecutor(factory)) {
executor.submit(() -> foo());
executor.submit(() -> bar());
}

void foo()  {
    try (ExecutorService executor = Executors.newUnboundedExecutor(factory)) {
        executor.submit(...);
}
}

void bar() {
    try (ExecutorService executor = Executors.newUnboundedExecutor(factory)) {
        executor.submit(...);
   
   
 }

}

In this example, the main task will not complete until foo and bar complete. The foo method, executing in a virtual thread, does not complete until the task that is submitted completes. Similarly bar, executing in another virtual thread, does not complete until the task that it submitted completes.

...