Producer doesn't wait for the consumer to be available

If the producer can check bulbs faster than the consumer can pack them, then most probably they will decide to have the following workflow:

  • The producer will check bulbs one by one and push them in a queue
  • The consumer will poll from the queue and pack the bulbs

Since the consumer is slower than the producer, the queue will hold checked but unpacked bulbs (we may assume that there is a low chance to have an empty queue). In the following diagram, we have the producer, the consumer, and the queue used for storing checked but unpacked bulbs:

In order to shape this scenario, we can rely on ConcurrentLinkedQueue (or LinkedBlockingQueue). This is an unbounded thread-safe queue based on linked nodes:

private static final Queue<String> queue 
= new ConcurrentLinkedQueue<>();

In order to push a bulb in the queue, the producer calls the offer() method:

queue.offer(bulb);

On the other hand, the consumer processes bulbs from the queue using the poll() method (since the consumer is slower than the producer, it should be a rare case when poll() will return null):

String bulb = queue.poll();

Let's start the assembly line for the first time for 10 seconds. This will output the following:

Starting assembly line ...
...
[2019-04-14 07:44:58] [INFO] Checked: bulb-827
[2019-04-14 07:44:59] [INFO] Checked: bulb-257
[2019-04-14 07:44:59] [INFO] Packed: bulb-827
...
Stopping assembly line ...
...
[2019-04-14 07:45:08] [INFO] Checked: bulb-369
[2019-04-14 07:45:09] [INFO] Packed: bulb-690
...
Assembling line was successfully stopped!

At this point, the assembly line is stopped, and in the queue, we have the following (these bulbs have been checked, but not packed):

[bulb-968, bulb-782, bulb-627, bulb-886, ...]

We restart the assembly line and check the highlighted lines, which reveal that the consumer resumes its job from where they'd stopped:

Starting assembly line ...
[2019-04-14 07:45:12] [INFO ] Packed: bulb-968
[2019-04-14 07:45:12] [INFO ] Checked: bulb-812
[2019-04-14 07:45:12] [INFO ] Checked: bulb-470
[2019-04-14 07:45:14] [INFO ] Packed: bulb-782
[2019-04-14 07:45:15] [INFO ] Checked: bulb-601
[2019-04-14 07:45:16] [INFO ] Packed: bulb-627
...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.72.212