It sounds like a toy to understand concurrency, so I haven't mentioned this before, but now I (upstairs, because it matters).
If it is intended for production code, do not collapse your own. There are many well-implemented (debugged) parallel data structures in java.util.concurrent. Use them.
When consuming, you do not need to disconnect your consumer based on "all items consumed." This is due to the state of the race, when the consumer can “move forward” the manufacturer and find an empty list only because the manufacturer has not yet written items for consumption.
There are several ways to shut down a consumer, but none of them can be done by viewing the data that will be consumed in isolation.
My recommendation is that the manufacturer "signals" the consumer when the manufacturer produces. Then the consumer will stop when he has both a “signal” and no more data, and the list is empty.
Alternative methods include creating a shutdown element. The producer adds a shutdown element, and the consumer only shuts down when the shutdown element is displayed. If you have a consumer group, keep in mind that you should not remove the shutdown item (or only one user will disconnect).
In addition, the consumer could “control” the producer, so if the producer is alive / alive and the list is empty, the consumer assumes that more data will become available. The shutdown occurs when the manufacturer is dead / does not exist and there is no data.
Which method you use will depend on the approach you choose and the problem you are trying to solve.
I know that people love elegant solutions, but if your only manufacturer knows about one consumer, the first option looks.
public class Producer { public void shutdown() { addRemainingItems(); consumer.shutdown(); } }
where the consumer looks like {
public class Consumer { private boolean shuttingDown = false; public void shutdown() { shuttingDown = true; } public void run() { if (!list.isEmpty() && !shuttingDown) {
Please note that such a lack of blocking of elements in the list is inherently dangerous, but you have indicated only one consumer, so there are no complaints about reading from the list.
Now, if you have several consumers, you need to provide protection to ensure that one element will not be pulled by two threads at the same time (and it needs to exchange data in such a way that all flows are disconnected).