Synchronizers: latches, barriers, semaphores question 48 of 180 senior
Why is Semaphore the right way to limit concurrency with virtual threads?
- It is not, a fixed thread pool is still correct
- Correct: Because the limit belongs to the resource, not to the thread count, and a semaphore says so directly
- Because virtual threads cannot use locks
- Because semaphores are faster on virtual threads
With platform threads, a pool of 20 did two jobs at once: it reused expensive threads, and it capped how many things happened at the same time. Virtual threads remove the first job, and people then discover the second one was load-bearing.
A semaphore expresses the cap where it belongs. One thread per task, and the permit count is the real constraint written down:
Semaphore db = new Semaphore(20); // the connection pool has 20 connections
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (var request : requests) {
executor.submit(() -> {
db.acquire();
try { return query(request); } finally { db.release(); }
});
}
}
Now a million tasks can be in flight while exactly 20 touch the database, and a reader can see which number belongs to which resource, instead of one pool size standing in for three unrelated limits.
Quiz yourself on Synchronizers: latches, barriers, semaphores Suggest a correction