Use of queue in java, and use of javaqueue

Source: Internet
Author: User

Use of queue in java, and use of javaqueue

At the same level as List and Set, the Queue interface inherits the Collection interface. The Queue List implements the Queue interface. The Queue interface narrow the access permission to the method of the Queue list (that is, when the parameter type in the method is Queue, it can only access the method defined by the Queue interface, rather than directly accessing the Queue list's non-Queue method), so that only the appropriate method can be used. BlockingQueue inherits the Queue interface.

 

A queue is a data structure. it has two basic operations: adding an element at the end of the queue and removing an element from the queue header means that the queue manages data in a first-in-first-out manner, if you try to add an element to a full blocking queue or remove an element from an empty blocking queue, it will cause thread blocking. blocking queues is a useful tool for multi-threaded cooperation. The worker thread can regularly store intermediate results in a blocking queue, while other worker thread can fetch intermediate results and modify them in the future. The queue automatically balances the load. If the first thread set is slower than the second, the second thread set will be blocked while waiting for the result. If the first thread set runs fast, it will wait for the second thread set to catch up. The following table shows the operations for blocking queues in jdk1.5:

 

AddIf the queue is full, an IIIegaISlabEepeplian exception is thrown.
RemoveRemoves and returns the element in the queue header. If the queue is empty, a NoSuchElementException exception is thrown.
ElementReturns the element in the queue header. If the queue is empty, a NoSuchElementException exception is thrown.
OfferAdd an element and return true. If the queue is full, return false.
PollRemoves and returns the element in the queue header. If the queue is empty, null is returned.
PeekReturns the element in the queue header. If the queue is empty, null is returned.
PutAdd an element. If the queue is full, it is blocked.
TakeRemove and return the elements in the queue header. If the queue is empty, it is blocked.

 

Remove, element, offer, poll, and peek are actually Queue interfaces.

Blocking queue operations can be divided into the following three types based on their response methods: aad, removee, and element operations throw an exception when you try to add an element to a full queue or retrieve an element from an empty queue. Of course, in multi-threaded programs, the queue may become full or empty at any time, so you may want to use the offer, poll, and peek methods. These methods only give an error when the task cannot be completed without throwing an exception.

 

Note: if an error occurs in the poll and peek methods, null is returned. Therefore, it is invalid to insert null values into the queue.

 

There are also offer and poll method variants with timeout, for example, the following call:
Boolean success = q. offer (x, 100, TimeUnit. MILLISECONDS );
Object head = q. poll (100, TimeUnit. MILLISECONDS );
 

Finally, we have put and take blocking operations. The put method is blocked when the queue is full, and the take method is blocked when the queue is empty.

 

The java. ulil. concurrent package provides four variants of the blocking queue. By default,LinkedBlockingQueueThere is no upper limit to the capacity of (not accurate, the capacity is Integer when not specified. MAX_VALUE), but you can also specify its maximum capacity. It is based on the linked list queue, Which is FIFO (first-in-first-out) sort element.


ArrayBlockingQueueDuring construction, you must specify the capacity and choose whether to enable fairness. If the fairness parameter is set to true, the thread with the longest wait time will be processed first (in fact, this fairness is achieved by setting ReentrantLock to true: that is, the thread with the longest wait time will operate first ). In general, fairness will make you pay the price for performance and use it only when it is really necessary. It is an array-based blocking loop queue column, which sorts elements according to the FIFO (first-in-first-out) principle.


PriorityBlockingQueueIt is a queue with a priority, rather than a first-in-first-out queue. The element is removed in the order of priority, and there is no upper limit to this queue. (after reading the source code, PriorityBlockingQueue is repackaged for PriorityQueue, which is based on the heap data structure, priorityQueue has no capacity limit. It is the same as ArrayList, so it will not be blocked when put is blocked on the queue first. Although this queue is logically unbounded, however, an OutOfMemoryError may occur when trying to add the queue because the resources are exhausted. However, if the queue is empty, the take operation of the element will be blocked, so its retrieval operation take is blocked. In addition, you must be able to compare the elements in the queue.


DelayQueue(Implemented based on PriorityQueue) is an unbounded blocking queue that stores Delayed elements. elements can be extracted only when the delay expires. The queue header is the Delayed element with the longest storage time after the delay expires. If the delay has not expired, the queue has no header and poll returns null. When the getDelay (TimeUnit. NANOSECONDS) method of an element returns a value smaller than or equal to zero, poll will remove the element upon expiration. The queue does not allow null elements. The following is the latency interface:

Java code

The compareTo method will also be implemented for the elements placed in DelayQueue, which is used by DelayQueue to sort the elements.

 

The following example shows how to use a blocking queue to control the thread set. The program searches for all files under a directory and all its subdirectories, and prints a list of files containing the specified keyword. From the following example, we can see that the two significant advantages of blocking queues are that multi-threaded operations in a common queue do not require additional synchronization, And the queue automatically balances the load, that is, the processing speed on the other side (both sides of production and consumption) will be blocked as soon as it is processed, thus reducing the processing speed gap between the two sides. The specific implementation is as follows:

Use of queue in Java code

At the same level as List and Set, the Queue interface inherits the Collection interface. The Queue List implements the Queue interface. The Queue interface narrow the access permission to the method of the Queue list (that is, when the parameter type in the method is Queue, it can only access the method defined by the Queue interface, rather than directly accessing the Queue list's non-Queue method), so that only the appropriate method can be used. BlockingQueue inherits the Queue interface.

 

A queue is a data structure. it has two basic operations: adding an element at the end of the queue and removing an element from the queue header means that the queue manages data in a first-in-first-out manner, if you try to add an element to a full blocking queue or remove an element from an empty blocking queue, it will cause thread blocking. blocking queues is a useful tool for multi-threaded cooperation. The worker thread can regularly store intermediate results in a blocking queue, while other worker thread can fetch intermediate results and modify them in the future. The queue automatically balances the load. If the first thread set is slower than the second, the second thread set will be blocked while waiting for the result. If the first thread set runs fast, it will wait for the second thread set to catch up. The following table shows the operations for blocking queues in jdk1.5:

 

AddIf the queue is full, an IIIegaISlabEepeplian exception is thrown.
RemoveRemoves and returns the element in the queue header. If the queue is empty, a NoSuchElementException exception is thrown.
ElementReturns the element in the queue header. If the queue is empty, a NoSuchElementException exception is thrown.
OfferAdd an element and return true. If the queue is full, return false.
PollRemoves and returns the element in the queue header. If the queue is empty, null is returned.
PeekReturns the element in the queue header. If the queue is empty, null is returned.
PutAdd an element. If the queue is full, it is blocked.
TakeRemove and return the elements in the queue header. If the queue is empty, it is blocked.

 

Remove, element, offer, poll, and peek are actually Queue interfaces.

Blocking queue operations can be divided into the following three types based on their response methods: aad, removee, and element operations throw an exception when you try to add an element to a full queue or retrieve an element from an empty queue. Of course, in multi-threaded programs, the queue may become full or empty at any time, so you may want to use the offer, poll, and peek methods. These methods only give an error when the task cannot be completed without throwing an exception.

 

Note: if an error occurs in the poll and peek methods, null is returned. Therefore, it is invalid to insert null values into the queue.

 

There are also offer and poll method variants with timeout, for example, the following call:
Boolean success = q. offer (x, 100, TimeUnit. MILLISECONDS );
Object head = q. poll (100, TimeUnit. MILLISECONDS );
 

Finally, we have put and take blocking operations. The put method is blocked when the queue is full, and the take method is blocked when the queue is empty.

 

The java. ulil. concurrent package provides four variants of the blocking queue. By default,LinkedBlockingQueueThere is no upper limit to the capacity of (not accurate, the capacity is Integer when not specified. MAX_VALUE), but you can also specify its maximum capacity. It is based on the linked list queue, Which is FIFO (first-in-first-out) sort element.


ArrayBlockingQueueDuring construction, you must specify the capacity and choose whether to enable fairness. If the fairness parameter is set to true, the thread with the longest wait time will be processed first (in fact, this fairness is achieved by setting ReentrantLock to true: that is, the thread with the longest wait time will operate first ). In general, fairness will make you pay the price for performance and use it only when it is really necessary. It is an array-based blocking loop queue column, which sorts elements according to the FIFO (first-in-first-out) principle.


PriorityBlockingQueueIt is a queue with a priority, rather than a first-in-first-out queue. The element is removed in the order of priority, and there is no upper limit to this queue. (after reading the source code, PriorityBlockingQueue is repackaged for PriorityQueue, which is based on the heap data structure, priorityQueue has no capacity limit. It is the same as ArrayList, so it will not be blocked when put is blocked on the queue first. Although this queue is logically unbounded, however, an OutOfMemoryError may occur when trying to add the queue because the resources are exhausted. However, if the queue is empty, the take operation of the element will be blocked, so its retrieval operation take is blocked. In addition, you must be able to compare the elements in the queue.


DelayQueue(Implemented based on PriorityQueue) is an unbounded blocking queue that stores Delayed elements. elements can be extracted only when the delay expires. The queue header is the Delayed element with the longest storage time after the delay expires. If the delay has not expired, the queue has no header and poll returns null. When the getDelay (TimeUnit. NANOSECONDS) method of an element returns a value smaller than or equal to zero, poll will remove the element upon expiration. The queue does not allow null elements. The following is the latency interface:

Java code

The compareTo method will also be implemented for the elements placed in DelayQueue, which is used by DelayQueue to sort the elements.

 

The following example shows how to use a blocking queue to control the thread set. The program searches for all files under a directory and all its subdirectories, and prints a list of files containing the specified keyword. From the following example, we can see that the two significant advantages of blocking queues are that multi-threaded operations in a common queue do not require additional synchronization, And the queue automatically balances the load, that is, the processing speed on the other side (both sides of production and consumption) will be blocked as soon as it is processed, thus reducing the processing speed gap between the two sides. The specific implementation is as follows:

Java code

Related Article

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.