Producer Consumer Problem Reentrant Lock

public class ProducerConsumerProblem {

public static void main(String[] args) throws InterruptedException {
Lock lock = new ReentrantLock();
List<Integer> buffer = new LinkedList<>();
Condition isEmpty = lock.newCondition();
Condition isFull = lock.newCondition();

ExecutorService executorService = Executors.newFixedThreadPool(2);
List<Callable<String>> list = new ArrayList<>();
list.add(new Producer(lock, buffer, isEmpty, isFull));
list.add(new Consumer(lock, buffer, isEmpty, isFull));
final List<Future<String>> futures = executorService.invokeAll(list);

futures.forEach(stringFuture -> {
try {
System.out.println("Done :" + stringFuture.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
System.out.println("ExecutorService Shutdown");
}
});
}

private static class Producer implements Callable<String> {
private Lock producerLock;
private List<Integer> buffer;
Condition isEmpty;
Condition isFull;

Producer(Lock lock, List<Integer> buffer, Condition isEmpty, Condition isFull) {
this.producerLock = lock;
this.buffer = buffer;
this.isEmpty = isEmpty;
this.isFull = isFull;
}


@Override
public String call() throws Exception {
int count = 1;
for (; count <= 50; count++) {
try {
producerLock.lock();
if (buffer.size() == 50) {
isFull.await();
}
buffer.add(1);
isEmpty.signalAll();
} finally {
producerLock.unlock();
}

}
return "Produced : " + (count - 1);
}
}

private static class Consumer implements Callable<String> {

private Lock consumerLock;
private List<Integer> buffer;
Condition isEmpty;
Condition isFull;

Consumer(Lock lock, List<Integer> buffer, Condition isEmpty, Condition isFull) {
this.consumerLock = lock;
this.buffer = buffer;
this.isEmpty = isEmpty;
this.isFull = isFull;
}


@Override
public String call() throws Exception {
int count = 1;
for (; count <= 50; count++) {

try {
consumerLock.lock();
if (buffer.isEmpty()) {
isEmpty.await();
}
buffer.remove(buffer.size() - 1);
isFull.signalAll();
} finally {
consumerLock.unlock();
}
}
return "Consumed : " + (count - 1);
}
}

}

No comments:

Post a Comment

Functional programming with Java - Part 1

 Recently I was reviewing one PR raised by team memeber and going through one utitlity method and found out there are too many muatable vari...