Java Java BlockingQueue interface. Util. Concurrent. BlockingQueue said a can access elements, and the thread safe queue. In other words, when multiple threads insert and retrieve elements from JavaBlockingQueue at the same time, there are no concurrency problems (elements are inserted multiple times, processed multiple times, etc.).

From Java BlockingQueue you can derive the concept of a BlockingQueue, which means that the queue itself can block threads to insert elements into the queue, or block threads to retrieve elements from the queue. For example, when a thread attempts to fetch an element from an empty queue, the thread will be blocked until the number of elements in the queue is no longer empty. Of course, whether or not a thread is blocked depends on what methods you call to get elements from BlockingQueue. Some methods block the thread, others throw exceptions, and so on, as we’ll explain in more detail below.

BlockingQueue interface implementation class

This article won’t cover how to implement the BlockingQueue interface yourself; JUC already has some interface implementation classes for you. BlockingQueue is a Java interface whose implementation class can be used when we need to use blocking queues. The java.util.concurrent package contains the following implementation classes that implement the BlockingQueue interface.

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

In this article and subsequent articles, we will introduce the functions and usage scenarios of these implementation classes, looking forward to your attention.

BlockingQueue application scenarios

BlockingQueueThis is usually applied when one thread produces objects in the queue while another thread consumes objects in the queue. The following illustration illustrates the usage scenario:

The producer thread continuously produces new objects and inserts them into the BlockingQueue until the number of objects in the queue reaches the maximum storage capacity of the queue. That is, when the number of objects in the queue reaches the upper limit, the producer thread blocks and cannot insert new objects into the queue. The producer thread will remain blocked until the consumer thread removes the Object from the queue, leaving the queue free to put a new Object in.

The consumer thread is constantly fetching objects from BlockingQueue and processing them. If the consumer thread tries to fetch 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.

Therefore BlockingQueue is often used as a buffer queue for production consumption. If you don’t want to use distributed or middleware message queues (Redis, Kafka, etc.) BlockingQueue can be an alternative if you don’t want to use distributed or middleware message queues (because for a small function it can add a large standalone middleware operation cost).

2.1.BlockingQueue method introduction

JavaBlockingQueue provides four different sets of methods for inserting, removing, and checking for an element object in a queue. Each set of methods has a different response behavior after being called, as follows:

An exception is thrown Return a specific value Block and wait Wait timeout after blocking
Insert the object add(o) offer(o) put(o) offer(o, timeout, timeunit)
Remove the object remove(o) poll() take() poll(timeout, timeunit)
Check object Exists element() peek()

The four behaviors of the above method are respectively

  1. Throw exception: Throw an exception if the result (empty or full queue) is not immediately responded to after the method is called.
  2. Return a specific value: If the method cannot respond immediately after being called (empty queue or full queue), a specific value (usually true/false) is returned, true indicating that the method succeeded, otherwise it failed.
  3. Block and wait: If a method is called and does not respond immediately (empty queue or full queue), the method will block and wait.
  4. Wait timeout after blocking: If a method is called and does not respond immediately to the result (empty queue or full queue), the method will be blocked and wait within a certain time range, that is, within the timeout range. When the timeout period is exceeded, the method thread will no longer block, but will return a specific value (usually true/ False), true indicating that the method executed successfully, otherwise indicating that the method failed.

Also, BlockingQueue does not allow null insertions into its queue. If you insert a NULL into the queue, a NullPointerException will be raised. Queues typically put objects in from the front of the queue and get objects from the back. BlockingQueue supports manipulating data objects not only from the front and back of the queue, but also from anywhere else in the queue. For example, you have put an object in the queue waiting to be processed, but for some specific reason you want it removed from the queue. You can call the remove(o) method to remove a particular O object from the queue. Of course, our program can’t do this very often, because queues are very inefficient data structures that often manipulate data from the middle, so it’s not recommended unless necessary.

add(o)

The BlockingQueueadd() method inserts the O object into the queue as an argument. If there is any free space in the queue, the o object will be inserted immediately. If there is no space left in the queue, the add() method will run out of IllegalStateException.

offer(o)

The BlockingQueueoffer() method inserts the O object into the queue as an argument. If there is any free space in the queue, the o object will be inserted immediately. If there is no space left in the queue, the offer() method returns the specified value false.

offer(o, long millis, TimeUnit timeUnit)

The BlockingQueueoffer() method has another version of its implementation with a timeout setting parameter. This version of the offer() method inserts the O object into the queue as an argument, and if there is any free space in the queue, it will be inserted immediately; If there is no space left in the queue, the thread calling the offer method will block and wait until the timeout. If there is no space left in the queue after the timeout, the offer() method will return false.

put(o)

The BlockingQueueput() method inserts the O object into the queue as an argument. If there is any free space in the queue, the o object will be inserted immediately. If there is no more space in the queue, the thread calling the PUT method will be blocked until there is more space in the BlockingQueue to put objects in.

take()

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

poll()

The BlockingQueuepoll() method fetches and removes the first element (object) in the queue, and returns NULL if the BlockingQueue does not contain any more elements.

poll(long timeMillis, TimeUnit timeUnit)

The BlockingQueuepoll(Long timeMillis, TimeUnit TimeUnit) method also has a time-out bound version, which normally retrieves and removes the first element (object) in the queue. If the BlockingQueue does not contain any elements, within the timeout period, this version of the poll() method will block and wait if no new objects are put on the queue; Poll (Long timeMillis, TimeUnit TimeUnit) returns null after the blocking time exceeds the timeout

remove(Object o)

The BlockingQueueremove(Object O) method removes an element Object given as an argument from the queue. The remove() method uses O.dice (element) to compare the passed argument o to the Object in the queue. To determine if the object to be deleted exists in the queue, remove it from the queue if it does and return true, otherwise return false.

Note that if there are multiple objects in the queue equal to the equals parameter passed in, deleting only one of them will not delete all matching objects in the queue.

peek()

The BlockingQueuepeek() method takes out the first element object in the queue, but does not remove it from the queue. If there are currently no elements in the queue, that is, empty, the peek() method returns NULL.

element()

The BlockingQueueelement() method retrieves the first element object in the queue, but does not remove it from the queue. The Element () method throws a NoSuchElementException if there are currently no elements in the queue, that is, an empty queue.

contains(Object o)

The BlockingQueuecontains(Object O) method is used to determine if there is an Object in the current queue that is equal to the passed argument O (objects.equals (o, element) is used to determine the equality of Objects). Iterating through all elements in the queue, this method returns true if a matching element object is found in the queue; This method returns false if none of the elements match.

drainTo(Collection dest)

The drainTo(Collection Dest) method retrieves all elements of the queue at once into the Collection Dest object.

drainTo(Collection dest, int maxElements)

The drainTo(Collection Dest) method retrieves maxElements from the queue once and stores them in the Collection Dest object.

size()

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

remainingCapacity()

BlockingQueueremainingCapacity () method returns the queue is still left how many available space to put the new object. Remaining capacity = Total capacity of the queue – Number of occupied space

Welcome to my blog, where there are many fine collections

  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.

Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.

  • Spring Boot2.0 by Hand
  • Spring Security- JWT-OAUTH2
  • RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
  • “Actual SpringCloud Micro-service from Bronze to King”
  • VUE Series