← Java

Java · 23 / 24

Virtual threads, cancellation and resource limits

Stop a waiting task and bound access to a scarce resource.

  • Large
  • Advanced
  • 90 min

Prerequisites: Interfaces and composition, Maven, modules and ports/adapters

In this tutorial
  1. Read the domain contract
  2. Start an isolated environment
  3. Verify success and failure
  4. Make a regression visible
  5. Extend the contract
  6. Explain the solution and its limits
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

JDK 21, Maven 3.9 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-20 on Linux x86_64. Tests count concurrently active tasks and check the limit and cancellation. An interrupt is a request. Non-interruptible library calls also need their own timeouts.

Many virtual threads do not create unlimited database connections. A semaphore bounds concurrent resource users to two. Release belongs in finally. A second test interrupts a waiting task deliberately. The code uses no preview API and runs on Java 21.

Package contents and individual files

01Read the domain contract

Virtual threads make many waiting tasks inexpensive. They do not enlarge a database or external API limit. A semaphore therefore limits entry into the scarce resource. finally must release an acquired permit even after failure.

src/main/java/tutorial/BoundedWork.java · javaOpen file
package tutorial;

import java.util.concurrent.*;

public class BoundedWork {

  private final Semaphore permits = new Semaphore(2);

  public void run(Callable<Void> work) throws Exception {
    permits.acquire();
    try {
      work.call();
    } finally {
      permits.release();
    }
  }

  public int available() {
    return permits.availablePermits();
  }
}

02Start an isolated environment

Java 21 is the language baseline. Maven resolves dependencies from the POM. Tests use their own data. HTTP tests start a server on a randomly assigned local port.

pom.xml · xmlOpen file
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>4.1.0</version></parent>
<groupId>learning</groupId><artifactId>tutorial</artifactId><version>1.0</version>
<properties><java.version>21</java.version></properties>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

</dependencies>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

03Verify success and failure

Tests count concurrently active tasks and check the limit and cancellation. An interrupt is a request. Non-interruptible library calls also need their own timeouts.

src/test/java/tutorial/LessonTest.java · javaOpen file
package tutorial;

import static org.junit.jupiter.api.Assertions.*;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import org.junit.jupiter.api.Test;

class LessonTest {

  @Test
  void boundedAndReleased() throws Exception {
    var work = new BoundedWork();
    var active = new AtomicInteger();
    var maximum = new AtomicInteger();
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
      var tasks = new ArrayList<Future<?>>();
      for (int i = 0; i < 20; i++) tasks.add(
        executor.submit(() -> {
          try {
            work.run(() -> {
              int n = active.incrementAndGet();
              maximum.accumulateAndGet(n, Math::max);
              try {
                Thread.sleep(5);
              } finally {
                active.decrementAndGet();
              }
              return null;
            });
          } catch (Exception e) {
            throw new RuntimeException(e);
          }
        })
      );
      for (var task : tasks) task.get(5, TimeUnit.SECONDS);
    }
    assertTrue(maximum.get() <= 2);
    assertEquals(2, work.available());
  }

  @Test
  void cancellationStopsWaitingTask() throws Exception {
    var started = new CountDownLatch(1);
    var stopped = new CountDownLatch(1);
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
      var future = executor.submit(() -> {
        started.countDown();
        try {
          Thread.sleep(60000);
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        } finally {
          stopped.countDown();
        }
      });
      assertTrue(started.await(2, TimeUnit.SECONDS));
      assertTrue(future.cancel(true));
      assertTrue(stopped.await(2, TimeUnit.SECONDS));
    }
  }
}

Run / check

mvn test
Expected result

Tests count concurrently active tasks and check the limit and cancellation. An interrupt is a request. Non-interruptible library calls also need their own timeouts.

04Make a regression visible

Change a domain expectation and rerun the test. Maven must report failure. A skipped database test is not evidence. Restore the correct expectation afterwards.

05Extend the contract

Make domain work throw an exception and verify available permits afterwards.

06Explain the solution and its limits

Both permits must remain available after failure. The test protects the finally boundary. A missing release path may otherwise appear only under load as an apparent stall. Copy solution/LessonTest.java over the test file and repeat the same verification.

Expected result

All tests pass, including the additional solution expectation.

Your exercise

Make domain work throw an exception and verify available permits afterwards.

Show the solution and explanation

Both permits must remain available after failure. The test protects the finally boundary. A missing release path may otherwise appear only under load as an apparent stall.

solution/LessonTest.java · javaOpen file
package tutorial;

import static org.junit.jupiter.api.Assertions.*;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import org.junit.jupiter.api.Test;

class LessonTest {

  @Test
  void failureReleasesPermits() {
    var work = new BoundedWork();
    assertThrows(IllegalStateException.class, () ->
      work.run(() -> {
        throw new IllegalStateException("injected");
      })
    );
    assertEquals(2, work.available());
  }

  @Test
  void boundedAndReleased() throws Exception {
    var work = new BoundedWork();
    var active = new AtomicInteger();
    var maximum = new AtomicInteger();
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
      var tasks = new ArrayList<Future<?>>();
      for (int i = 0; i < 20; i++) tasks.add(
        executor.submit(() -> {
          try {
            work.run(() -> {
              int n = active.incrementAndGet();
              maximum.accumulateAndGet(n, Math::max);
              try {
                Thread.sleep(5);
              } finally {
                active.decrementAndGet();
              }
              return null;
            });
          } catch (Exception e) {
            throw new RuntimeException(e);
          }
        })
      );
      for (var task : tasks) task.get(5, TimeUnit.SECONDS);
    }
    assertTrue(maximum.get() <= 2);
    assertEquals(2, work.available());
  }

  @Test
  void cancellationStopsWaitingTask() throws Exception {
    var started = new CountDownLatch(1);
    var stopped = new CountDownLatch(1);
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
      var future = executor.submit(() -> {
        started.countDown();
        try {
          Thread.sleep(60000);
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        } finally {
          stopped.countDown();
        }
      });
      assertTrue(started.await(2, TimeUnit.SECONDS));
      assertTrue(future.cancel(true));
      assertTrue(stopped.await(2, TimeUnit.SECONDS));
    }
  }
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.