views:

772

answers:

3

I am working on a project that uses a queue that keeps information about the messages that to be sent to remote hosts. In that case one thread is responsible to put the information into the queue and another thread is responsible for get the pop the information from the queue and send. In that case the 2nd thread needs to check the queue for the information periodically.

But later I found that it is a "Reinvention of Wheel" :) I could use a blocking queue for this purpose.

Now my question is What are the other advantages of using a blocking queue for above application? (Ex : Performance, Modifiable of the code, Any special tricks etc )

+1  A: 

They key thing you eliminate with the blocking queue is 'polling'. This is where you say

In that case the 2nd thread needs to check the queue for the information periodically.

This can be very inefficient - using much unnecessary CPU time. It can also introduce unneeded latencies.

Foredecker
+2  A: 

This article has a good discussion on this.

drinks milk
+5  A: 

The main advantage is that a BlockingQueue provides a correct, thread-safe implementation. Developers have implemented this feature themselves for years, but it is tricky to get right. Now the runtime has an implementation developed, reviewed, and maintained by concurrency experts.

The "blocking" nature of the queue has a couple of advantages. First, on adding elements, if the queue capacity is limited, memory consumption is limited as well. Also, if the queue consumers get too far behind producers, the producers are naturally throttled since they have to wait to add elements. When taking elements from the queue, the main advantage is simplicity; waiting forever is trivial, and correctly waiting for a specified time-out is only a little more complicated.

erickson