Language syntax

Virtual thread resource limits

Bound resource use, not the number of submitted tasks.

Formal Syntax & Structure

java syntaxjava
Semaphore permits = new Semaphore(capacity)

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 {        Semaphore slots = new Semaphore(2);        AtomicInteger active = new AtomicInteger(), peak = new AtomicInteger();        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {            List<Future<Integer>> jobs = new ArrayList<>();            for (int id : List.of(1,2,3,4,5,6)) jobs.add(executor.submit(() -> {                if (!slots.tryAcquire(3, TimeUnit.SECONDS)) throw new TimeoutException("capacity");                int now = active.incrementAndGet();                try { peak.accumulateAndGet(now, Math::max); return id*10; }                finally { active.decrementAndGet(); slots.release(); }            }));            int sum = 0; for (var f : jobs) sum += f.get(3, TimeUnit.SECONDS);            System.out.println(sum);        }        System.out.println(peak.get() >= 1 && peak.get() <= 2);        System.out.println(slots.availablePermits());    }}
Java Reference