What is the best method to get objects out of a BlockingQueue, in a concurrent program, without hitting a race condition? I’m currently doing the following and I’m not convinced it is the best method:
BlockingQueue<Violation> vQueue; /* in the constructor I pass in a BlockingQueue object full of violations that need to be processed - cut out for brevity */ Violation v; while ( ( v = vQueue.poll(500, TimeUnit.MILLISECONDS) ) != null ) { // do stuff with the violation }
I have yet to hit a race condition… but, I’m none too sure if this is truly safe.
This example was taken from the JDK 1.6 docs of
BlockingQueue. So You can see that you are doing it the right way. Here’s the quote which tells you that it have to work: