Versions Compared

Key

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

...

An early of prototype of Project Loom had API named FiberScope to support the scheduling of fibers (a precursor to virtual threads) with initial support in this area. 

There is no explicit support in the current prototype but it is possible to use existing constructs without needing too many new APIs. In particular, ExecutorService has been retrofitted to extend AutoCloseable so that it’s possible to write code like this:

ThreadFactory factory = Thread.builderofVirtual().virtual().factory()
try (ExecutorService executor = Executors.newThreadExecutor(factory)) {
    executor.submit(task1);
    executor.submit(task2);
}

...

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

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

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

}

...


var deadline = Instant.now().plusSeconds(2);
try (ExecutorService executor = Executors.newVirtualThreadExector().withDeadline(deadline)) {
    executor.submit(task1);
    executor.submit(task2);
}

...


try (ExecutorService executor1 = Executors.newVirtualThreadExecutor().withDeadline(deadline)) {
try (ExecutorService executor2 = Executors.newVirtualThreadExecutor(factory)) {
executor2.submit(task1);
executor2.submit(task2);
}
}

...