Blocking IO and downstream limits
What you will learn
Cheap threads do not make a scarce connection, socket, or remote API unlimited. Limit the actual resource with a semaphore, give acquisition and I/O deadlines, and release permits in finally. Separately limit incoming work to control memory and queue growth.
- Apply a permit limit around a finite simulated downstream call.
- Test cancellation without leaking permits.
- Distinguish pinning behavior on Java 21 and Java 24 or later.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. The stable examples use finite submissions, cooperative tasks and executor ownership. The fixture runner also enforces a process deadline.
Reject an exhausted resource
import java.util.*;import java.util.concurrent.*;import java.util.concurrent.atomic.*;public class Main {
public static void main(String[] args) throws Exception { Semaphore permits = new Semaphore(1); permits.acquire(); try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { System.out.println(executor.submit(() -> permits.tryAcquire(0, TimeUnit.MILLISECONDS)).get(3, TimeUnit.SECONDS)); } finally { permits.release(); } System.out.println(permits.availablePermits()); }}Expected output:
false1The resource is unavailable while the owner holds its only permit. Zero wait provides a deterministic overload case.
Capacity and admission
A semaphore bounds the number of concurrent operations holding a permit; it does not bound the number of waiting tasks. Apply admission control before submitting a large workload, and define overload rejection or a timed wait. Release only when acquisition succeeded. Real downstream I/O needs its own deadlines and cleanup; an outer Future.get timeout by itself does not stop the task.
Pinning is version-sensitive
On Java 21, a virtual thread blocked while holding an intrinsic monitor may retain its carrier. JDK 24 changed monitor implementation (JEP 491), reducing this limitation for synchronized blocks and methods. Native or foreign calls and certain runtime operations can still pin. Do not mechanically replace every synchronized block with ReentrantLock on newer JDKs. Long critical sections and contention remain problems regardless of pinning.
Inspect before optimizing
Use JFR events and a thread dump, e.g. on a test-owned JVM jcmd <pid> Thread.dump_to_file -format=json threads.json. JFR virtual-thread events and pinning diagnostics depend on JDK version; verify the event configuration. Avoid collecting sensitive application data. Compare equivalent workloads, warm up, record CPU and latency, and do not infer speed from this small demo.
Bound a finite batch of downstream calls
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()); }}Expected output:
210true2Peak may be one or two depending on scheduling. The invariant, not an exact interleaving, is the assertion. This represents a synthetic local call, not real network I/O.
Interrupt a permit holder
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(1); CountDownLatch entered = new CountDownLatch(1), gate = new CountDownLatch(1), released = new CountDownLatch(1); try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { Future<Void> job = executor.submit(() -> { slots.acquire(); try { entered.countDown(); gate.await(3, TimeUnit.SECONDS); return null; } finally { slots.release(); released.countDown(); } }); try { if (!entered.await(3, TimeUnit.SECONDS)) throw new AssertionError("not entered"); System.out.println(job.cancel(true)); if (!released.await(3, TimeUnit.SECONDS)) throw new AssertionError("not released"); System.out.println(slots.availablePermits()); } finally { gate.countDown(); } } }}Expected output:
true1Future cancellation requests interruption; the release latch demonstrates actual cleanup rather than assuming cancelled means stopped.
Release on downstream failure
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(1); try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { Future<Integer> job = executor.submit(() -> { slots.acquire(); try { throw new IllegalStateException("synthetic failure"); } finally { slots.release(); } }); try { job.get(3, TimeUnit.SECONDS); } catch (ExecutionException e) { System.out.println(e.getCause().getClass().getSimpleName()); } } System.out.println(slots.availablePermits()); }}Expected output:
IllegalStateException1The task reports its failure and frees the resource.
Common mistakes
Never release a permit after an unsuccessful acquisition. Do not use a semaphore alone to accept unlimited requests. Do not claim Java 24 eliminated all pinning. Avoid sleeping while holding a lock in examples meant to demonstrate correctness.
Practice
Simulate a single scarce slot. First hold it in the owner and verify a virtual task cannot acquire it immediately. Release it and run a second task that acquires, returns 7 and releases it.
Expected output:
false71Compare your answer with the manual practice criteria.
Official reading: Semaphore · Virtual threads · JDK 24 changes · Diagnostics. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Blocking IO and downstream limits — knowledge check
Original virtual-thread and versioned concurrency questions.
What does a semaphore with two permits bound?
What should happen if tryAcquire returns false?
What changed in JDK 24?
Does Future.cancel(true) guarantee cleanup has finished?
How should a service limit its workload?