238. Solving the producer-consumer problem via virtual threads (fixed via Semaphore)
In the previous problem, we implemented the producer-consumer problem via a fixed number of producers (three virtual threads) and consumers (two virtual threads). Moreover, since our application works as an assembly line, we can say that the number of tasks is boundless. Practically, the producers and consumers work without breaks until the assembly line is stopped. This means the virtual threads assigned by the executor as producers and consumers remain exactly the same between a start-stop lifecycle of the assembly line.
Next, let’s assume that we want to use Semaphore
objects instead of newVirtualThreadPerTaskExecutor()
to obtain the exact same behavior.
Based on Problem 235, we can implement the fixed number of producers as follows:
private final static Semaphore producerService
= new Semaphore(PRODUCERS);
...
for (int i = 0; i < PRODUCERS; i++) {
Thread.ofVirtual(...