blocking queues in Java

Source: Internet
Author: User

1. What is a blocking queue?

A blocking queue (Blockingqueue) is a queue that supports two additional operations. The two additional actions are that when the queue is empty, the thread that gets the element waits for the queue to become non-null. 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 provide four ways to handle this:

Method \ Handle throws exception return special value blocking timeout exit Insert method Add (E) offer (e) put (e,time,unit) to remove          Method of Remove () poll () Take () poll () Check methods Element () Peek () Unavailable, not available

Throw an exception: refers to the illegalstateexception ("Queue full") exception thrown when the blocked queue is filled and the element is inserted into the queue. When the queue is empty, the nosuchelementexception exception is thrown when the element is fetched from the queue.

Returns a special value: The Insertion method returns success and returns True. To remove a method, you take an element out of the queue, and if not, return null

Blocking: When the blocked queue is full, if the producer threads put elements into the queue, the queue blocks the producer thread until it gets the data, or the response breaks out. When the queue is empty, the consumer thread attempts to take elements from the queue, and the queue blocks the consumer thread until the queue is available.

Timeout exit: When the blocked queue is full, the queue blocks the producer thread for a period of time, and if more than a certain amount of time, the producer thread exits.

2. Blocking queues in Java

The JDK7 provides 7 blocking queues. respectively is

Arrayblockingqueue: A bounded blocking queue consisting of an array structure.

Linkedblockingqueue: A bounded blocking queue consisting of a list structure.

Priorityblockingqueue: An unbounded blocking queue that supports priority sorting.

Delayqueue: An unbounded blocking queue implemented using a priority queue.

Synchronousqueue: A blocking queue that does not store elements.

LinkedTransferQueue: An unbounded blocking queue consisting of a list structure.

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);
  

The fairness of the visitor is implemented using a reentrant lock, as follows:

public arrayblockingqueue (int capacity, Boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException ();
        This.items = new Object[capacity];
        lock = new Reentrantlock (fair);
        Notempty = Lock.newcondition ();
        Notfull =  lock.newcondition ();
}
  

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.

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: info-contact@alibabacloud.com 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.