How to resume my thread that is in a blocking process due to linkedBlockingQueue.take()

99 views Asked by At

I have a producer thread which will keep inserting values into a linkedBlockingQueue and have multiple consumer thread that will take() from this linkedBlockingQueue concurrently. My condition for them to keep thinking is when my flag for producer has finished is false and they will stop trying to take when it is true. however i met with the issue whereby my second thread is in the take() block process. I believe it is because before my producer set the flag to true when it ends, one of the tread is already inside the run() body executing the take() blocking method. As there wont be any new element added into linkedBlockingQueue, it will be in a forever blocking processs. How can i rectify this issue?

2

There are 2 answers

3
javaHunter On BEST ANSWER

A standard way to solve this problem is by making the producer thread insert some poison values (some special value that you choose) in the shared queue when it is done. You should put a number of poison values equal to numOfThreads.

In the consumer thread, whenever you take a value, you check if the value is a poison value. If it is, you can just return.

1
outdev On

You can interrupt the thread that is waiting on take(), so take() will throw InterruptedException, which is caught, so execution will go into the catch clause.