Java Concurrent Programming Tool Class JUC Part 1: BlockingQueue Blocking Queue

The Java BlockingQueue interface java.util.concurrent.BlockingQueuerepresents a thread-safe queue that can access elements. In other words, when multiple threads BlockingQueueinsert elements and get elements from Java at the same time, it will not cause any concurrency problems (element is inserted multiple times, processed multiple times, etc.).

BlockingQueueA concept can be derived from java : blocking queue means that the queue itself can block the thread from inserting elements into the queue, or block the thread from obtaining elements from the queue. For example: when a thread tries to get elements from an empty queue , the thread will be blocked until the number of elements in the queue is no longer empty. Of course, whether the thread will be blocked depends on what method you call to BlockingQueueget the element. Some methods will block the thread, some methods will throw exceptions, etc. We will introduce them in detail below.

One, BlockingQueue interface implementation class

This article will not introduce how to implement the BlockingQueueinterface by yourself . JUC has already prepared some related interface implementation classes for us. BlockingQueueIt is a java interface. When we need to use a blocking queue, we can use its implementation class. java.util.concurrentThere are some implementation classes in the package that implement BlockingQueueinterfaces as follows .

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

In this article and subsequent articles, I will introduce the functions and usage scenarios of these implementation classes in turn, and look forward to your attention.

Two, BlockingQueue application scenario introduction

BlockingQueueIt is usually used in a scenario where one thread produces objects into the queue, and at the same time another thread consumes the objects in the queue. The following picture illustrates the usage scenario:

The producer thread continuously produces new objects and inserts them BlockingQueueuntil the number of objects in the queue reaches the upper limit of the queue storage capacity. That is to say, when the objects in the queue reach the upper limit of capacity, the producer thread will be blocked and no new objects can be inserted into the queue. The producer thread will remain blocked and wait until the consumer thread removes the Object from the queue, allowing the queue to have free space in the new object.

The consumer thread continuously BlockingQueuefetches the object and processes it. If the consumer thread tries to obtain an object from an empty queue, the consumer thread will be blocked in a waiting state until the producer puts a new object into the queue.

So BlockingQueue is often used as a buffer queue for production and consumption. If you don't want to use distributed or middleware message queues (redis, kafka), etc. (because a small function will increase the operation and maintenance cost of a relatively large independent middleware), BlockingQueue It may be an alternative option.

2.1. Introduction to the BlockingQueue method

Java BlockingQueueprovides four different sets of methods for inserting, removing, and checking that an element object is contained in the queue. Each set of methods differs in their response behavior after being called, as follows:

Throw an exception Return a specific value Waiting after blocking Waiting timeout after blocking
Insert object add(o) offer(o) put(o) offer(o, timeout, timeunit)
Remove object remove(o) poll() take() poll(timeout, timeunit)
Check object existence element() peek()

The meanings of the four behaviors of the above method are

  1. Throw an exception : If the result cannot be responded to immediately after calling the method (empty queue or full queue), an exception will be thrown.
  2. Return a specific value : If the result cannot be responded to immediately after calling the method (empty queue or full queue), a specific value (usually true/false) is returned, true means the method is executed successfully, otherwise it means the method fails to execute.
  3. Waiting after blocking : If the method cannot be responded to the result immediately after calling the method (empty queue or full queue), the method will be blocked and kept in the waiting state.
  4. Waiting for timeout after blocking : If the method cannot be responded to the result immediately (empty queue or full queue) after calling the method, the method will be blocked waiting for a certain period of time, that is, blocked within the timeout period. When the timeout period expires, the method thread will no longer block, but return a specific value (usually true/false), true means that the method is executed successfully, otherwise it means that the method fails to execute.

In addition, the BlockingQueuequeue is not allowed to insert null into it. If you insert null into the queue, an NullPointerExceptionexception will be thrown . The general queue is to put objects from the head of the team and get objects from the end of the team. It BlockingQueuenot only supports the operation of data objects from the head of the queue, but also supports the operation of data from any other position in the queue. For example: You have put an object in the queue and waiting to be processed, but for some special reason you want to delete this object from the queue. You can call remove(o)methods to delete a specific o object in the queue. Of course, our program can't do this frequently, because the data structure of the queue is often very inefficient to manipulate data from the middle position, so unless necessary, it is not recommended to do so.

add(o)

The BlockingQueue add()method can insert the o object into the queue as a parameter. If there is remaining space in the queue, it will be inserted immediately; if there is no remaining space in the queue, the add()method will run out of IllegalStateException.

offer(o)

The BlockingQueue offer()method can insert the o object into the queue as a parameter. If there is remaining space in the queue, it will be inserted immediately; if there is no remaining space in the queue, the offer()method will return a specific value false.

offer(o, long millis, TimeUnit timeUnit)

offer()There is another version of the BlockingQueue method, and there is a timeout setting parameter. This version of the offer()method inserts the o object into the queue as a parameter. If there is remaining space in the queue, it will be inserted immediately; if there is no remaining space in the queue, the thread calling the offer method will be blocked within the timeout period and will be in a waiting state , When the blocking time is greater than the timeout time, if there is still no space left in the queue to put a new object, the offer()method will return false.

put(o)

The BlockingQueue put()method can insert the o object into the queue in the form of a parameter. If there is remaining space in the queue, it will be inserted immediately; if there is no remaining space in the queue, the thread calling the put method will be blocked until a new block is made available in the BlockingQueue The space can be put into the object so far.

take()

The BlockingQueue take()method takes out and removes the first element (object) in the queue. If the BlockingQueue queue does not contain any elements, take()the thread calling the method will be blocked until a new element object is inserted into the queue.

poll()

The BlockingQueue poll()method takes out and removes the first element (object) in the queue. If the BlockingQueue queue does not contain any elements, the poll()method will return null.

poll(long timeMillis, TimeUnit timeUnit)

The BlockingQueue poll(long timeMillis, TimeUnit timeUnit)method also has a version with a timeout limit. Normally, this method takes out and removes the first element (object) in the queue. If the BlockingQueue queue does not contain any elements, within the timeout period, if there are still no new objects placed in the queue, this version of the poll()method will be blocked in a waiting state; when the blocking time is greater than the timeout period, poll(long timeMillis, TimeUnit timeUnit)returnnull

remove(Object o)

The BlockingQueue remove(Object o)method can delete an element object given in the form of a parameter from the queue. The remove()method uses o.equals(element)a one-to-one comparison between the incoming parameter o and the object in the queue to determine whether the object to be deleted exists in the queue, and if it exists, Remove from the queue and return true, otherwise return false.

It should be noted that if there are multiple objects in the queue equal to the incoming parameter equals, only one of them will be deleted, and all matching objects in the queue will not be deleted.

peek()

The BlockingQueue peek()method will take out the first element object in the queue, but will not delete it from the queue. If there are currently no elements in the queue, that is, an empty queue, the peek()method will return null.

element()

The BlockingQueue element()method will take out the first element object in the queue, but will not delete it from the queue. If there are currently no elements in the queue, that is, an empty queue, the element()method will throw NoSuchElementException.

contains(Object o)

The BlockingQueue contains(Object o)method is used to determine whether there is an object in the current queue, which is equal to the incoming parameter o ( Objects.equals(o, element)used to determine the equality of objects). Traverse all the elements in the queue. Once a matching element object is found in the queue, this method will return true; if no elements match equal, this method will return false.

drainTo (Collection dest)

drainTo(Collection dest)The method takes out all the elements in the queue at one time and saves them in the Collection dest object of the collection class.

drainTo (Collection dest, int maxElements)

drainTo(Collection dest)The method removes maxElements elements from the queue at one time and saves them in the Collection dest object of the collection class.

size()

The BlockingQueue size()method returns how many elements are currently in the queue

remainingCapacity()

The BlockingQueue remainingCapacity()method will return how much free space is left in the queue for placing new objects. Remaining space capacity = total capacity of the queue-the amount of space that has been occupied

Welcome to follow my blog, there are many boutique collections

  • This article is reproduced indicate the source (en must not turn only the text): letters Gebo off .

If you think it is helpful to you, please like and share it for me! Your support is my inexhaustible creative motivation! . In addition, the author has output the following high-quality content recently, and I look forward to your attention.

Guess you like

Origin blog.csdn.net/hanxiaotongtong/article/details/115060233