Detailed BlockingQueue concurrent containers

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/ThinkWon/article/details/102508901

About BlockingQueue

In actual programming, often used in various containers JDK Collection implemented as a set of frame List, Map, Queue Interface containers, these containers are substantially not thread safe, except that it can convert Collections thread-safe container, Doug Lea masters as we prepare the corresponding thread-safe container, such as the implementation of the List interface CopyOnWriteArrayList ( about CopyOnWriteArrayList can see this article ), implementation of the Map interface ConcurrentHashMap ( about ConcurrentHashMap can see this article ), to achieve Queue interfaces ConcurrentLinkedQueue ( about ConcurrentLinkedQueue can see this article ).

The most common " producer - consumer " problem, often considered queue thread operations between the data container, so that service can decouple the function of each module, the producer "production" data out of the data is placed in container, consumers only need to carry on to obtain data in the "data container", so the producer thread and a consumer thread can be decoupled and only focus on their business function. Blocking queue (BlockingQueue) is widely used in "producer - consumer" problem, the reason is BlockingQueue provides a method of insertion and removal can be blocked. When the queue container is full, the producer thread will be blocked until the queue is not full; when the queue is empty the container, the consumer thread will be blocked until the time until the queue is not empty.

Basic Operations

BlockingQueue basic operation is summarized as follows (in this figure derived JAVA API documentation):

Here Insert Picture Description

BlockingQueue inherited Queue interface, therefore, the basic operation of the data elements:

Insert elements

  1. add (E e): insert data to the queue, when the queue is full, the insertion element throws an IllegalStateException;

  2. offer (E e): When the inserted data to the queue, returns successfully inserted true, otherwise it returns false. When the queue is full will not throw an exception;

Removing elements

  1. remove (Object o): Delete data from the queue, success is returned true, otherwisefalse

  2. poll: deleting data, when the queue is empty, return null;

View element

  1. element: obtaining head elements, NoSuchElementException an exception is thrown if the queue is empty;
  2. peek: obtaining head elements, if the queue is empty, an exception is thrown NoSuchElementException

BlockingQueue having special operations:

Insert data:

  1. put: When the blocking queue capacity is full, the queue data is inserted into the blocking thread is blocked until the blocking queue has available spare capacity;

  2. offer (E e, long timeout, TimeUnit unit): If the blocking queue is full, it will clog the thread insert data until the blocking queue has spare place, and put different methods, the method will have a timeout If the current exceeds a given timeout, insert data thread exits;

delete data

  1. take (): When blocking queue is empty, the head of the team acquiring thread data will be blocked;
  2. poll (long timeout, TimeUnit unit): When blocking queue is empty, the data acquisition thread is blocked, in addition, if the blocked thread exceeds a given length of time, the thread exits

Commonly used BlockingQueue

BlockingQueue implement interfaces have ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedTransferQueue, PriorityBlockingQueue, SynchronousQueue, and that several common queue is blocked in the actual programming will be commonly used, following several common of these blocking queue explained:

1.ArrayBlockingQueue

ArrayBlockingQueue is achieved by an array bounded blocking queue. The command queue element FIFO (First In First Out). Thus, the presence of data elements longest queue when the head element, while the end of the current queue is the latest data of the data element. ArrayBlockingQueue as "bounded data buffer", the data producer is inserted into the queue container, extraction by the consumer. ArrayBlockingQueue Once created, the capacity can not be changed.

When the queue is full capacity, try to put into the queue will cause the operating element blocking; attempt to remove an element from an empty queue will also block.

ArrayBlockingQueue default can not guarantee the fairness of the threads access the queue, the so-called fairness refers to the absolute chronological order in strict accordance waiting threads that can wait for the first thread first visit to ArrayBlockingQueue. Rather than fairness refers to the sequential access ArrayBlockingQueue not comply with a strict chronological order, there may, once ArrayBlockingQueue can be accessed, for a long time blocked thread is still inaccessible to ArrayBlockingQueue. If the guarantee fairness, generally decreases throughput . If you need ArrayBlockingQueue fairness, may be employed the following code:

private static ArrayBlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<Integer>(10,true);

About implementation principle ArrayBlockingQueue, you can look at this article .

2.LinkedBlockingQueue

LinkedBlockingQueue linked list implementation is bounded blocking queue FIFO also satisfies the characteristic of having a higher throughput compared with ArrayBlockingQueue with them, in order to prevent LinkedBlockingQueue capacity increases rapidly, a large amount of memory loss. When you create an object usually LinkedBlockingQueue will specify the size, if not specified, the capacity is equal to Integer.MAX_VALUE

3.PriorityBlockingQueue

PriorityBlockingQueue is a priority - unbounded blocking queue. By default sort order using natural elements, may be implemented by a custom class the compareTo () method to specify the elements collation, collation or specified by the constructor parameter Comparator initialization.

4.SynchronousQueue

SynchronousQueue each insert operation must wait for another thread corresponding deletion, therefore, SynchronousQueue not actually store any data element, because only when you delete data thread, other threads to insert data. Likewise, if you currently have thread insert data, the thread can delete data. SynchronousQueue You can also assign fairness by the constructor parameter.

5.LinkedTransferQueue

LinkedTransferQueue is unbounded blocking queue of a linked list data structure constituted, the queue TransferQueue implements the interface, there are the following differences in comparison with other methods of blocking queue:

transfer (E e)
If there is a current thread (the consumer) is calling take () method, or may delay the poll () method of consumption data, the producer thread can call transfer method to pass data to the consumer thread. If no, then the consumer thread, the thread producers will insert data into the tail until consumers can consume to exit;

tryTransfer (E E)
tryTransfer method if you currently have the consumer thread (call methods or take the poll method has a timeout feature) are consuming the data, which data can be transmitted immediately to the consumer thread, the thread consumption if no consumer data then it returns immediately false. Therefore, compared with the transfer method, transfer method is when consumers must wait until the thread consumption data, the producer thread to be able to return. The method can return results tryTransfer quit immediately.

tryTransfer (E e, long timeout,
imeUnit unit) and transfer the same basic functions, but increase the timeout feature, if the consumer is not only within the timeout period specified data consumption, then it is returned false.

6.LinkedBlockingDeque

LinkedBlockingDeque based bounded blocking deque linked list data structure, create the object if the size is specified, the default size of Integer.MAX_VALUE. Compared with LinkedBlockingQueue, the main difference is that, LinkedBlockingDeque having characteristics deque. LinkedBlockingDeque basic operation as shown below (from java files)

Here Insert Picture Description

As shown above, the basic operation LinkedBlockingDeque can be divided into four types: a special case, throwing an exception; 2 special circumstances, such as null or special value return false; 3 operating condition is not satisfied when the thread, the thread... It is blocked until the condition is satisfied; 4 operating a timeout feature.

Further, LinkedBlockingDeque achieved BlockingDueue interfaces is achieved LinkedBlockingQueue BlockingQueue, the main difference between these two interfaces are shown below (from java document):

Here Insert Picture Description

As can be seen from the figure, two interface function is equivalent to use, such a method and the add function BlockingQueue addLast BlockingDeque method is the same.

7.DelayQueue

DelayQueue is a repository for data Delayed interface unbounded blocking queue only when the delay time data in order to achieve the object is inserted into the queue for storage. If all current data have not yet reached to create a specified delay period, the queue is no team head, and thread through the acquisition of data elements such as poll method returns null. The so-called data delay expires, then through the interface Delayed getDelay(TimeUnit.NANOSECONDS)determination is performed, if the method returns a zero or less then the full data element of the delay period.

Guess you like

Origin blog.csdn.net/ThinkWon/article/details/102508901