I saw a piece of code in this question that I could not understand (most likely due to the fact that I am new to this area). This question refers to "a state of obvious race, where sometimes the producer finishes, signals this, and ConsumerWorkers stops before consuming everything in line."
In my opinion, isRunning will only be installed on the consumer after the manufacturer decides not to add more items to the queue. Thus, if the consumer thread sees isRunning as FALSE, and then sees that inputQueue is empty, then there is no way to add something to the queue in the future. Obviosuly, I am mistaken and something is missing, since no one who answered this question said that the scenario of the question is impossible. So, can anyone explain what sequence of events causes this race condition?
In fact, I see a problem with something else. For example, if several consumer threads saw that the producer isRunning, and they say that the queue has ONE element, many threads can enter a blocked take. If the STOPS producer now, while one thread exits take, the other threads are blocked on take forever. Interestingly, no one who answered this question pointed to this problem. So, my understanding of this is also probably wrong ?!
I did not want to add this as a comment to this question, since this is an old question, and my doubts will never get an answer! I will copy / post the code from this question here for a quick reference.
public class ConsumerWorker implements Runnable{ private BlockingQueue<Produced> inputQueue; private volatile boolean isRunning = true; public ConsumerWorker(BlockingQueue<Produced> inputQueue) { this.inputQueue = inputQueue; } @Override public void run() {
java multithreading synchronization race-condition producer-consumer
brainOverflow Apr 21 '13 at 18:20 2013-04-21 18:20
source share