Java concurrency Programming blocking queue detailed _java

Source: Internet
Author: User

1. What is a blocking queue?
A queue is a data structure that has two basic operations: adding an element to the end of the queue and removing an element from the queue header. The difference between a blocking team and a regular queue is that the normal queues do not block the current thread, and when faced with a similar consumer-producer model, additional synchronization policies and thread wakeup strategies are required. Blocking queues will block the current thread, and when the queue is empty, fetching elements from the queue will be blocked, and when the queue is full, the action to add elements to the queue will be blocked.


2, the main blocking queue and its methods

There are several main blocking queues available under the Java.util.concurrent package, mainly the following:

1) Arrayblockingqueue: Blocking queues based on array implementations must specify their capacity size when creating Arrayblockingqueue objects, as well as the ability to specify access policies, which are inequitable by default, that is, the thread with the longest waiting time is not guaranteed to have access to the queue.
2), Linkedblockingqueue: A blocking queue that is based on a linked list, the default size is Integer.max_value when the Linkedblockingqueue object is created without specifying the capacity size.
3, the above 2 kinds of queues are advanced first out of the queue, and Priorityblockingqueue is not, it will be based on the priority of the elements of the elements sorted, in order to prioritize the team, each team out of the elements are the highest priority element. Note that this blocking queue is an unbounded blocking queue, that is, the capacity has no upper limit (it can be known through the source, it does not have a container full of signal flags), the first 2 kinds are bounded queues.
4), Delayqueue: Based on Priorityqueue, a delay-blocking queue, the element in the delayqueue can be retrieved from the queue only if its specified delay time is up. Delayqueue is also a unbounded queue, so the operations (producers) that insert data into the queue are never blocked, and only the operations (consumers) that get the data are blocked.

The blocking queue includes most of the methods in the Non-blocking queue and provides several other useful methods:

The Put method is used to save the element to the tail of the team and wait if the queue is full;
The Take method is used to take the first element from the team and wait if the queue is empty;
The Offer method is used to save the element to the tail of the team, and if the queue is full, wait for a certain amount of time, return False if the time limit is reached, or return true if it has not been inserted successfully;
Poll method is used to take the first element from the team, if the queue is empty, then wait for a certain time, when the time limit is reached, if it is taken, then return null;

Let's look at a piece of code:

Import Java.util.concurrent.ArrayBlockingQueue;

/** 
 * @author Author: Jian Xu  e-mail:anxu_2013@163.com 
 * @version Date Created: March 20, 2016 PM 12:52:53 
 * Class Description
* * public class Blockingqueue
{public
  static void Main (string[] args) throws Interruptedexception
  {
    java.util.concurrent.blockingqueue<string> blockingqueue = new arrayblockingqueue<> (5);
    for (int i = 0; i < i++)
    {
      //Add the specified element to this queue
      blockingqueue.put ("add element" + i);
      System.out.println ("adding elements to the blocking queue:" + i);
    }
    System.out.println ("End of program to this run, imminent exit----");
  }


When the number of blocked queues is 5 o'clock, after 5 elements have been added, continuing to add will block the wait outside the queue, when the program does not terminate.

  

When the queue is full, we remove the first element of the team, you can continue to add elements to the blocking queue, the code is as follows:

public class Blockingqueue
{public
  static void Main (string[] args) throws Interruptedexception
  {
    java.util.concurrent.blockingqueue<string> blockingqueue = new arrayblockingqueue<> (5);
    for (int i = 0; i < i++)
    {
      //Add the specified element to this queue
      blockingqueue.put ("add element" + i);
      SYSTEM.OUT.PRINTLN ("adds element to the blocking queue:" + i);
      if (i>=4)
        System.out.println ("Remove team first element" +blockingqueue.take ());
    }
    System.out.println ("End of program to this run, imminent exit----");
  }

The results of the implementation are as follows:

  

3, the implementation of blocking queue principle
The following main look at the implementation of the principle of arrayblockingqueue.

First look at the member variables for the Arrayblockingqueue class:

public class Arrayblockingqueue<e> extends abstractqueue<e>
    implements Blockingqueue<e>, java.io.Serializable {

  /** bottom storage Structure-array *
  final object[] items;

  /** team First element subscript *
  /int takeindex;

  /** Team Tail Element subscript *
  /int putindex;

  Total/** queue elements
  /int count;

  /** Lock
  /FINAL reentrantlock lock;

  /** notempty Waiting conditions * *
  private final Condition notempty;
  /** notfull Waiting conditions * *
  private final Condition notfull;
  /**
   * Shared State for currently active iterators, or null if there
   * are known is not. Allows queue operations to update
   * iterator state.
   * *
  transient Itrs Itrs = null;

As you can see, the arrayblockingqueue used to store an element is actually an array.

Look at the implementation of the Arrayblockingqueue two important methods, put () and take ():

public void put (e e) throws Interruptedexception
  {
    //check E for empty
    Checknotnull (e) first;
    Get lock
    final reentrantlock lock = This.lock;
    Lock.lockinterruptibly ();
    Try
    {
      //When the queue is full, enter the condition wait while
      (count = = items.length)
        notfull.await ();
      Queue dissatisfaction, proceed into queue operation
      Enqueue (e);
    } 
    Finally
    {
      //release lock
      Lock.unlock ();
    }
  }

Look at the specific team operation:

private void Enqueue (E x)
  {
    final object[] items = this.items;
    Team Tail
    Items[putindex] = x;
    if (++putindex = = items.length)
      putindex = 0;
    Total number of queues +1
    count++;
    Notempty the waiting set of the condition to randomly select a thread to unblock its blocking state
    notempty.signal ();
  }

The following is the source code for the Take () method:

Public E take () throws Interruptedexception
  {
    //Acquire lock
    final reentrantlock lock = This.lock;
    Lock.lockinterruptibly ();
    Try
    {
      //queue for null
      while (count = = 0)
        /thread joins Notempty conditional wait set
        notempty.await ();
      Non-empty, out queue return
      dequeue ();
    } finally
    {
      //release lock
      Lock.unlock ();}
  }

4, the application of blocking queues: to achieve consumer-producer model

/** * @author Author: Jian Xu e-mail:anxu_2013@163.com * @version Date Created: March 20, 2016 2:21:55 * Class Description: Blocking queue implementation of consumer-producer Mode * * Publi
  C class Test {private int queuesize = 10;
  Private arrayblockingqueue<integer> queue = new arrayblockingqueue<integer> (queuesize);
    public static void Main (string[] args) {test test = new test ();
    Producer Producer = Test.new Producer ();
    Consumer Consumer = Test.new Consumer ();
    Producer.start ();
  Consumer.start ();
    Class Consumer extends Thread {@Override public void run () {consume ();
          private void Consume () {while (true) {try {queue.take ();
        System.out.println ("Take an element from the queue, queue remaining" + queue.size () + "element");
        catch (Interruptedexception e) {e.printstacktrace ();
    Class Producer extends Thread {@Override public void run () {produce ());
   private void Produce () {while (true) {try {queue.put (1);
        SYSTEM.OUT.PRINTLN ("Inserts an element into the queue, the queue remaining space:" + (Queuesize-queue.size ()));
        catch (Interruptedexception e) {e.printstacktrace ();
 }
      }
    }
  }
}

The above is the entire content of this article, I hope to help you learn.

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.