Home java BlockingQueue When, why and for what?

BlockingQueue When, why and for what?




I have an idea how this class works, but I want to understand what kind of situation it will bring me benefits, I can not even think of, help please figure out.

Answer 1, Authority 100%

blockingqueue is the queue queue with the following additions:

  • Blocking operation take () – takes the next element if the queue is empty – blocks execution before the element appears (until the moment when it stops being empty)
  • Blocking operation PUT (E E) – It is placed in the queue if the queue is filled – blocks execution until the place is released in the queue and the successful room in it.

Designed to implement the interaction “Supplier – Consumer”. The implementation of the methods of thread-safe (synchronized), so and write to it, and you can read from it in several threads. Quote from Javadoc:

Note That A BlockingQueue Can Safely Be Used With Multiple Producers
And Multiple Consumers .

Example 1:
Let there be a store with 3 inputs and 2 cashiers. Buyers rod through 3 entrances and go through 2 cashiers. The queue in the cash register. It is advisable to store buyers queue in BlockingQueue .

Example 2:
There is a conveyor producing details. For the production needs of the workpiece. From several machines of the previous stage of production, billets are coming, robots take them and make items from them. At the next stage, these details are used to produce knots by other robots. It is advisable to store the queue of incoming blanks and the queue of outgoing parts (for the next step) in BlockingQueue .

Answer 2, authority 41%

blockingqueue – How can I understand from the documentation used for In order to perform an operation on the data in another place or time, not where they were obtained.

The most common example is the message processing (data update). Receive data (opening event) in one thread (there may be several) and recorded in BlockingQueue, at the same time other then (he should be one) is waiting in the queue elements (the method of take), and as soon begins to receive data processing. This avoids the situation when several streams are trying to write down the same data.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions