Uses concurrent queue.

This commit is contained in:
Tanmay 2022-08-24 14:00:09 +01:00
parent 7dbf8cb992
commit a0ce9a6817
3 changed files with 6 additions and 10 deletions

View File

@ -24,10 +24,8 @@ public class Consumer implements Runnable {
throw new RuntimeException("Error acquiring semaphore " + e); throw new RuntimeException("Error acquiring semaphore " + e);
} }
if (store.size() > 0) { store.remove();
store.remove(); System.out.println("Consumed: " + name + " Left units :" + store.size());
System.out.println("Consumed: " + name + " Left units :" + store.size());
}
forProducer.release(); forProducer.release();

View File

@ -25,10 +25,8 @@ public class Producer implements Runnable {
throw new RuntimeException("Error acquiring semaphore " + e); throw new RuntimeException("Error acquiring semaphore " + e);
} }
if (store.size() < maxSize) { store.add(new UnitOfWork());
store.add(new UnitOfWork()); System.out.println("Produced: " + name + " Left units :" + store.size());
System.out.println("Produced: " + name + " Left units :" + store.size());
}
forConsumer.release(); forConsumer.release();
} }

View File

@ -1,8 +1,8 @@
package com.scaler.producerconsumer; package com.scaler.producerconsumer;
import java.util.ArrayDeque;
import java.util.Queue; import java.util.Queue;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -12,7 +12,7 @@ public class Runner {
private static final Set<String> consumerNames = Set.of("c1", "c2", "c3", "c4"); private static final Set<String> consumerNames = Set.of("c1", "c2", "c3", "c4");
public static void main(String[] args) { public static void main(String[] args) {
Queue<UnitOfWork> store = new ArrayDeque<>(); Queue<UnitOfWork> store = new ConcurrentLinkedDeque<>();
int maxSize = 20; int maxSize = 20;
Semaphore forProducer = new Semaphore(maxSize); Semaphore forProducer = new Semaphore(maxSize);