Blocking queues in Java detailed introduction _java

Source: Internet
Author: User
Tags diff sorts

blocking queues in Java

1. What is a blocking queue?

A blocking queue (Blockingqueue) is a queue that supports two additional operations. The two additional actions are:

When the queue is empty, the thread that gets the element waits for the queue to become non-empty.
When the queue is full, the thread that stores the elements waits for the queue to be available.

Blocking queues are often used by producers and consumers, and producers are threads that add elements to the queue, and consumers are the threads that take elements from the queue. A blocking queue is a container in which the producer stores elements, and the consumer takes only the elements from the container.

Blocking queues in the 2.Java

Seven blocking queues are available in the JDK:

    1. Arrayblockingqueue: A bounded blocking queue consisting of an array structure.
    2. Linkedblockingqueue: A bounded blocking queue consisting of a list structure.
    3. Priorityblockingqueue: An unbounded blocking queue that supports priority sorting.
    4. Delayqueue: An unbounded blocking queue implemented using a priority queue.
    5. Synchronousqueue: A blocking queue that does not store elements.
    6. LinkedTransferQueue: An unbounded blocking queue consisting of a list structure.
    7. Linkedblockingdeque: A two-way blocking queue consisting of a linked list structure.


Arrayblockingqueue is a bounded blocking queue implemented with arrays. This queue sorts the elements according to the first-in first out (FIFO) principle. By default, visitors are not guaranteed a fair access queue, the so-called fair Access queue is the blocking of all producer threads or consumer threads, when the queue is available, you can access the queue in a blocking sequence, that is, the first blocked producer thread, you can first insert elements into the queue, first blocked consumer threads, You can get the elements from the queue first. Typically, the throughput is reduced to ensure fairness . We can create a fair blocking queue using the following code:

Arrayblockingqueue fairqueue = new Arrayblockingqueue (1000,true);

For the fairness of its access, it is achieved through the Reentrantlock lock.


Linkedblockingqueue is a bounded blocking queue implemented with a linked list. The default and maximum length for this queue is integer.max_value. This queue sorts the elements according to the FIFO principle.


Priorityblockingqueue is an unbounded queue that supports precedence. By default, the elements are sorted in a natural order, or you can specify the collation of the elements through the comparer comparator. The elements are sorted in ascending order.


Delayqueue is an unbounded blocking queue that supports delay-fetching elements. Queues are implemented using Priorityqueue. The elements in the queue must implement the delayed interface, and you can specify how long to get the current element from the queue when the element is created. The element can be extracted from the queue only when the delay expires. We can apply delayqueue to the following scenarios:

Caching system Design: You can use Delayqueue to save the expiration of the cache element, use a thread loop query Delayqueue, when the element can be obtained from delayqueue, the cache expiration date.

Scheduled task scheduling. Use Delayqueue to save the task and execution time that will be performed on that day, once you get the task from the Delayqueue to start execution, from example Timerqueue is the use of delayqueue implementation.

How to implement delayed interface

We can refer to the Scheduledfuturetask class in Scheduledthreadpoolexecutor. This class implements the delayed interface. First: When an object is created, when the object can be used with the time record, the code is as follows:

Scheduledfuturetask (Runnable R, V result, long NS, long period) {
      super (R, result);
      This.time = ns;
      This.period = period;
      This.sequencenumber = Sequencer.getandincrement ();

You can then use Getdelay to query the current element for how long it will take, and the code is as follows:

Public long Getdelay (timeunit unit) {return
 Unit.convert (Time-now (), timeunit.nanoseconds);

Through the constructor can see the delay time parameter NS unit is nanosecond, it is best to use nanosecond when you design, because Getdelay can specify any unit, once in nanoseconds as a unit, and delay time and precision less than nanosecond on the trouble. When used, note that when time is less than current, Getdelay returns a negative number.

Finally, we can use time to specify its order in the queue, for example: let the longest delay time at the end of the queue.

public int CompareTo (delayed other) {
      if (other = this) return 
      if (other instanceof scheduledfuturetask) {
        scheduledfuturetask x = (scheduledfuturetask) Other;
        Long diff = time-x.time;
        if (diff < 0)
        else if (diff > 0) return
    else if (SequenceNumber < x.sequencenumber)
        else return
    Long d = (Getdelay (timeunit.nanoseconds)-other.getdelay (timeunit.nanoseconds));
      return (d = = 0)? 0: ((d < 0)? -1:1);

How to implement delay blocking queues

The implementation of the delay blocking queue is simple, when the consumer gets the element from the queue, the current thread is blocked if the element does not reach the delay time.

Long delay = First.getdelay (timeutil.nanoseconds);
if (delay<=0) {return
 Q.poll;/blocking Queue
}else if (leader!=null) {
  //leader represents a thread
  waiting to be fetched from the blocking queue Available.await (); Let the thread enter the wait signal
}else {
//when leader is NULL, set the current thread to leader thread
Thisthread = Thread.CurrentThread ();
leader = Thisthread;
Use the Awaitnanos () method to let the current thread wait to receive a signal or wait for delay time
Available.awaitnanos (delay);
} finally{
 if (leader==thisthread) {


Synchronousqueue is a blocking queue that does not store elements. Each put operation must wait for a take operation, or you cannot continue adding elements. Synchronousqueue can be seen as a passer, responsible for the direct transmission of data from producer threads to consumer threads. The queue itself does not store any elements, and is ideal for transitive scenarios, such as data used in one thread, passed to another thread, and synchronousqueue throughput is higher than

Linkedblockingqueue and Arrayblockingqueue.

It supports fair access queues. A policy mechanism that is still unjust by default


LinkedTransferQueue is an unbounded blocking Transferqueue queue composed of a list structure. Trytransfer and transfer methods are linkedtransferqueue compared to other blocking queues.

Transfer method

If a consumer is currently waiting for the receiving element (the consumer uses the Take () method or the poll () method with a time limit), the transfer method can immediately transfer (transmit) to the consumer the elements passed in by the producer. If no consumer waits for the receiving element, the transfer method stores the element in the tail node of the queue and waits until the element is consumed by the consumer before returning.

Trytransfer method

is used to test whether the incoming elements of a producer can be passed directly to the consumer. Returns False if there is no consumer waiting to receive the element. The difference between the transfer method and the Trytransfer method is that the method returns immediately, regardless of whether the consumer receives it. The transfer approach is to wait until the consumer is consumed before returning.

For the Trytransfer (e E, long timeout, Timeunit unit) method with time limits, it is an attempt to pass the element passed on by the producer directly to the consumer, but if no consumer consumes the element, waits for the specified time to return, if the timeout is not consumed, Returns False if the element is consumed within the time-out period, returns true.


Linkedblockingdeque is a two-way blocking queue consisting of a list structure. The so-called two-way queue means that you can insert and remove elements from both ends of the queue. Two-terminal queue because of a more than one operation queue entrance, in the simultaneous entry of multithreading, also reduced by half the competition. Compared to other blocking queues, Linkedblockingdeque is more addfirst,addlast,offerfirst,offerlast,peekfirst,peeklast and so on, with the method ending with the word, the insertion, Gets (peek) or removes the first element of a two-terminal queue. The method that ends the last word, which represents inserting, getting, or removing the final element of a two-terminal queue. In addition, insert method add is equivalent to AddLast, and removing method remove is equivalent to Removefirst. But the take approach is equivalent to Takefirst, not knowing if it is a JDK bug, or using a method with the one and last suffixes to make it clearer. The capacity of the queue can be initialized when the linkedblockingdeque is initialized to prevent the transition from expanding when it is again expanded. In addition, bidirectional blocking queues can be used in "work-stealing" mode.

Thank you for reading, I hope to help you, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.