J.VI · Java 25 practice question
Consider the following Java code running on a system using Java 25's virtual threads. A `Semaphore` initialized with 1 permits is used to guard access to a critical resource. Which of the following best describes the behavior when multiple virtual threads attempt to acquire the permit?
import java.util.concurrent.Semaphore;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class SemaphoreDemo {
public static void main(String[] args) throws InterruptedException {
Semaphore semaphore = new Semaphore(1);
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
for (int i = 0; i < 3; i++) {
executor.submit(() -> {
try {
System.out.println("Thread " + Thread.currentThread().getId() + " attempting to acquire...");
semaphore.acquire();
try {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired permit and accessing resource.");
Thread.sleep(100); // Simulate work
} finally {
semaphore.release();
System.out.println("Thread " + Thread.currentThread().getId() + " released permit.");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
executor.shutdown();
// Wait for tasks to complete (in a real test, we'd use join/await)
}
}
Check answer and explanation
Correct answer: Only the first thread to call `semaphore.acquire()` will succeed; the others will block until the permit is released.
Explanation
A `Semaphore` initialized to 1 acts as a mutex (mutual exclusion lock). When multiple threads, whether they are platform threads or virtual threads, call `acquire()` when no permits are available, the subsequent calls will block until another thread calls `release()`. Virtual threads benefit from low overhead but do not bypass core synchronization mechanisms like semaphores.
Common trap
Learners might mistakenly assume that the nature of virtual threads negates the need for explicit synchronization primitives like Semaphores, leading them to select A or D.
Source: Java SE 25 Documentation for Semaphore: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/Semaphore.html
Checked against the cited text on 2026-11-27.