"Java concurrent programming art" of blocking queue

Two blocking queue is a queue support additional operations. These two additional operational support insertion and removal method of blockage:

1) supports blocking insertion method: When the queue is full, block the execution queue insertion thread
2) supports blocking removal method: When the queue is empty, the queue will block the thread execution removal

Methods:

The method / approach Throw an exception Returns the special value Has been blocked Timeout exit
Insertion method add(e) offer(e) put(e) offer(e, time, unit)
Removal Method no poll() take() poll(time, unit)
Detection method element() peek() no no
  • Throws an exception: When the queue is full, insert element throws IllegalStateException;
  • Returns special value: offer () method is enqueue, when inserted successfully returns true, the insert fails return false; poll () is dequeued, the return value of the element when a team successfully, the queue is empty or null
  • It has been blocked: When the queue is full, the thread insertion method of blocking execution; when the queue is empty, blocked a thread of execution team approach
  • Timeout Exit: As the name suggests

In JDK7 in, Java blocking queue a total of seven, each class inherits AbstractQueue:

  • ArrayBlockingQueue
  • LinkedTransferQueue
  • SynchronousQueue
  • DelayQueue
  • LinkedBlockingDeque
  • LinkedBlockingQueue
  • PriorityBlockingQueue

ArrayBlockingQueue

Such is achieved by an array bounded blocking queue, the queue of elements arranged according to the principles of the FIFO. The thread does not guarantee fair access to the queue, the so-called fair access means that the blocked thread, blocking access to the queue according to the order, which is to first blocked access by default. Fair access is realized by a fair lock of ReentrantLock:

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();
}
  1. Because an array created directly, ArrayBlockingQueue length can not be changed,
  2. When set to ReentrantLock fair locks, all subsequent Lock competition will be fair competition, not seen Condition principles of small partners think, that and Condition do with it? The answer is in the Condition wakes up to take part in the competition Lock, we will comply with fair competition in Lock competition.

LinkedBlockingQueue

This class is a linked list to achieve bounded blocking queue (also not bounded, simply because the counter can count up to Integer.MAX_VALUE). The default and maximum length of this queue is Integer.MAX_VALUE. The elements are arranged according to the FIFO principle.

PriorityBlockingQueue

This class is a support unbounded blocking priority queue. Take natural elements are sorted in ascending order by default. Custom class may implement the compareTo () to specify the collation element, or to specify the sort of initialization Comparator element.
See: pit not fill in, fill bit later

DelayQueue

Support delay retrieving an element of unbounded blocking queue. Use queue PriorityQueueis implemented, the queue element must implement Delayed interfaces, and then create the element can be specified how long it takes to get the current primary colors from the queue, only elements extracted from the queue when the delay has expired.
Use scenarios:

  • Design caching system: You can save cache element with DelayQueue validity, using a thread loop query DelayQueue, once DelayQueue in from acquiring element that represents the cache valid until the
  • Timing task scheduling: tasks and execution time DelayQueue saved the day will be executed once DelayQueue get from the start to the task execution, such as TimerQueue

Implementation process is as follows:

First, implement Delayedthe interface:
java @Override public long getDelay(TimeUnit unit){ // 返回当前元素还需要等待多久,当返回<0的值时,表示可以出队;>0时,表示仍需要等待 }

The second step, each time the offer (), to PriorityQueueinsert elements on their own, the sort in ascending order according to the natural

The third step, each time you get (call to take (), in order to have the blocking function), if the time will be less than before blocking

for (;;) {
    E first = q.peek();
    if (first == null)
        available.await();
    else {
        long delay = first.getDelay(NANOSECONDS);
        if (delay <= 0)
            return q.poll();
        first = null; // don't retain ref while waiting
        if (leader != null)
            available.await();
        else {
            Thread thisThread = Thread.currentThread();
            leader = thisThread;
            try {
                available.awaitNanos(delay);
            } finally {
                if (leader == thisThread)
                    leader = null;
            }
        }
    }
}

Specific can see: to understand the DelayQueue

SynchronousQueue

Not a storage element of the queue, the production of a producer, a consumer spending, each put operation requires waiting for a take action. The queue is responsible for processing the data producer thread thread passed on to consumers. More suitable for the transfer of the scene. And its throughput is higher than ArrayBlockingQueue LinkedBlockingQueue

LinkedTransferQueue

This class adds two main methods: transfer()and tryTransfer()
transfer()mainly when the consumer thread while waiting, a producer produces elements, immediately handed over to the consumer, you do not need additional enqueue operation; if the consumer is not waiting , on the first team into the tail.
tryTransfer()Are producers used to test the elements can be passed directly to consumers.

Specific can see: to understand the LinkedTansferQueue

to sum up

  • ArrayBlockingQueue
  • LinkedBlockingQueue
  • LinkedBlockingDeque
  • SynchronousQueue
    above four is relatively simple, data structures and the respective methods are not elaborated on the relatively simple. The remaining three are relatively big head, and relatively new, it intends to carry out alone explain

This chapter is a rough look at other features blocking queue, for some unusual classes, will follow up on detailed analysis (in fact, the first wave of supplementary data structures and algorithms)

Guess you like

Origin www.cnblogs.com/codeleven/p/10963265.html