Here is another set of codes that test on using semaphore to constraint concurrency with 1M virtual threads
Java:
import java.util.concurrent.*;
void main() throws Throwable {
final int MAX = 100_000;
final int CONCURRENCY = 1;
final Semaphore avail = new Semaphore(CONCURRENCY, true);
final CountDownLatch latch = new CountDownLatch(MAX);
for (int i = 0; i < MAX; i++) {
final int ii = i;
Thread.startVirtualThread(() -> {
try {
avail.acquire();
System.out.printf("THREAD %d WORKING. %d IN QUEUE\n", ii, avail.getQueueLength());
avail.release();
latch.countDown();
}
catch (Throwable t) {}
});
}
latch.await();
}
You don't need to use any thread pooling since virtual threads are super lightweight.
You just need to use semaphore to control concurrency and/or reentrantlock for critical sections.
You should also test out on Generational ZGC.
With virtual threads, it means you get to write synchronous codes which are easier to reason and let the JVM does the context switching for you.
Since it is a LTS release, that means you get a longer support term, depending on which distributor you are using.
