Producer-consumer produce one item and immediately consume(Java)

987 Views Asked by At

According to GeeksforGeeks-ProducerConsumerProblem, I am confused with the second exercise:

Try to make your program produce one item and immediately after that the consumer consumes it before any other item is produced by the consumer.

How to solve it? I think after the producer produces an item, we can just record the size after the producer add an item to the list. And while(list.size() == recordSize) wait(); Is it correct? Thank you for your time.

4

There are 4 best solutions below

1
On

You can use a flag variable and everytime you want to produce an item you need to verify that this flag is false. (The flag is True if you have already produced an item so you can't produce another one until you know the consumer has handled it, You should protect the value of this flag with synchronized). now, if the flag is false, add an item and then wait() or else just wait() for the consumer to consume it, and then use notify() in the consumer code to keep going. you should also use wait() in the consumer code to wait until the producer produce an item, and then when you finish use notify() and wait() to wait to new item.

0
On

A think the problem can be solved by using SynchronousQueue

You can also read more about it here and here

This is a better alternative then using own syncronization constructs.

2
On

The producer can either can leave a Future for the consumer to populate. The producer then calls the Future's get() method, which will cause the producers thread to stop until the consumer finishes. This solution is modern in nature as it is the way to is done in the wild. The same can be done using a CountDownLatch. The difference between the latch and the future is that a Future is used when the producer needs to generate an object that is required by the holder of the Future object. Whereas a CountDownLatch is used primarily for synchronizing multiple threads.

Though to make Future or CountDOwnLatch work in this example would require some changes to the problem, for example the LinkedList will have to pass more than just an Integer. An easier solution would be to swap out the LinkedList with a SynchronousQueue. A SynchronousQueue contains zero elements in it, so when an item is inserted into the queue, the queue blocks until a consumer comes and takes the item. Further attempts to put an object into the SynchronousQueue will block until the item is consumed. The producer can attempt to put the enxt item into the queue before the producer finishes with the previous one, but it will again wait there for the consumer to come along and get it.

0
On

Replace while (list.size() == capacity) with while (list.size() == 1). By doing this, producer will produce only 1 item and wait for consumer to consume it.