0

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?

10e5x
  • 909
  • 4
  • 15
  • 27

2 Answers2

2

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.

javaHunter
  • 1,097
  • 6
  • 9
  • Do you mind helping me think of some poison value that is nv possible to be a file name?And how can i get out of the run() method? – 10e5x Dec 02 '14 at 13:18
  • Thanks i do a forever while loop then break out of it. However my poison value is "endOfWorkQueue" dont think it is an unique enuff value for fileName...still there is a possible where ppl will enter this as a file name – 10e5x Dec 02 '14 at 13:38
  • To exit the run just call return. For the File Name check this: http://stackoverflow.com/questions/1976007/what-characters-are-forbidden-in-windows-and-linux-directory-names. In windows a file Name can't contain: \/:?*<>| – javaHunter Dec 02 '14 at 13:42
0

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.

outdev
  • 5,249
  • 3
  • 21
  • 38