Language syntax
Owned virtual thread tasks
Close the executor at the ownership boundary; arrange cooperative cancellation.
Formal Syntax & Structure
java syntaxjava
try (var executor = Executors.newVirtualThreadPerTaskExecutor())Working Example
Example Snippetjava
import java.util.*;import java.util.concurrent.*;import java.util.concurrent.atomic.*;public class Main {
public static void main(String[] args) throws Exception { try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { Future<Integer> price = executor.submit(() -> 120); Future<Integer> fee = executor.submit(() -> 15); try { System.out.println(Math.addExact(price.get(3, TimeUnit.SECONDS), fee.get(3, TimeUnit.SECONDS))); } finally { price.cancel(true); fee.cancel(true); } } }}