Use of queue in Java

Source: Internet
Author: User

The queue interface is the same level as list and set, and both inherit the collection interface. LinkedList implements the queue interface. The queue interface narrows the access to the LinkedList method (that is, if the parameter type in the method is a queue, it is only possible to access the method defined by the queue interface and not directly to the LinkedList non-queue method). So that only appropriate methods can be used. Blockingqueue inherits the queue interface.

A queue is a data structure. It has two basic operations: adding an element to the tail of the queue, and removing an element from the head of the queue that is, the queue manages the data in a first-in, in-and-out manner if you attempt to add an element to an already full block queue or remove a single cell from an empty blocking queue, causing the thread to block. Blocking queues is a useful tool when working with multiple threads. Worker threads can periodically store intermediate results in a blocking queue while other worker thread threads take intermediate results out and modify them in the future. The queue automatically balances the load. If the first set of threads runs slower than the second, the second line threads blocks when it waits for the result. If the first set of threads runs fast, it waits for the second set of threads to catch up. The following table shows the actions of the blocking queue in jdk1.5:


Add a meta-cable if the queue is full, throw a Iiiegaislabeepeplian exception
Remove removes and returns the element of the head of the queue if the queue is empty, a Nosuchelementexception exception is thrown
Element returns the elements of the queue header if the queue is empty, a Nosuchelementexception exception is thrown
Offer add an element and return true if the queue is full, return false
Poll removing and returning elements to the queue header returns null if the queue is empty
Peek returns the element of the queue header returns null if the queue is empty
Put adds an element block if the queue is full
Take remove and return elements of the queue header if the queue is empty, it blocks
Remove, element, offer, poll, peek are actually belong to the queue interface.


Blocking queues can be divided into three categories based on how they respond: The AAD, Removee, and element operations throw exceptions when you try to add elements to a full queue or to get elements from an empty queue. Of course, in multithreaded programs, the queue can become full or empty at any time, so you might want to use the offer, poll, peek method. These methods only give an error when the task cannot be completed and do not throw an exception.

Note: The poll and Peek methods fail in to return NULL. Therefore, inserting a null value into the queue is not legal.

There are also variants of offer and poll methods with timeouts, for example, the following call:
Boolean success = Q.offer (X,100,timeunit.milliseconds);
Attempts to insert an element into the tail of the queue within 100 milliseconds. If successful, returns true immediately; otherwise, when the timeout is reached, the return is false. Similarly, call:
Object head = Q.poll (timeunit.milliseconds);
If the queue header element has been successfully removed within 100 milliseconds, the element is immediately returned, otherwise null will return when the timeout is reached.

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

The Java.ulil.concurrent package provides 4 variants of a blocking queue. By default, the capacity of the Linkedblockingqueue is unlimited (said inaccurate, when not specified when the capacity is integer.max_value, do not say how can be blocked when put), but you can also choose to specify its maximum capacity, it is based on the list of the queue, This queue sorts elements by FIFO (first-in, in-out).

Arrayblockingqueue need to specify the capacity at the time of construction, and can choose whether to need fairness, if the fairness parameter is set to True, the longest waiting thread will be processed first (in fact, by setting Reentrantlock to True to This fairness is achieved: the thread that waits for the longest time is the first to operate. In general, fairness makes you pay for performance, and you can use it only when you really need it. It is an array-based blocking loop queue, which sorts elements by FIFO (first in, out) principle.

The Priorityblockingqueue is a queue with priority, not a FIFO queue. elements are removed in order of priority, and there is no upper limit for the queue (look at the source code, Priorityblockingqueue is the re-packaging of Priorityqueue, is based on the heap data structure, and priorityqueue is no capacity limit, As with ArrayList, the put on the priority block queue is not blocked. Although this queue is logically unbounded, the attempt to perform an add operation may result in a outofmemoryerror if the resource is exhausted, but if the queue is empty, then the operation take of the element is blocked, so its retrieval operation takes is blocked. In addition, the elements that go into the queue are more capable.

Finally, Delayqueue (based on Priorityqueue) is an unbounded blocking queue that holds delayed elements that can be extracted only from the expiration of the delay. The head of the queue is the Delayed element with the longest save time after the delay expires. If the delay has not expired, the queue does not have a header, and poll returns NULL. When an element's Getdelay (Timeunit.nanoseconds) method returns a value less than or equal to zero, the expiration occurs, and poll removes the element. This queue does not allow the use of NULL elements. Here is the delay interface:

Java code
Public interface Delayed extends comparable<delayed> {
Long Getdelay (timeunit unit);
}
The elements put into delayqueue will also implement the CompareTo method, Delayqueue Use this to sort the elements.

The following example shows how to use a blocking queue to control the set of threads. The program searches all files in a directory and all its subdirectories, and prints a list of files containing the specified keywords. As can be seen from the following example, the use of blocking queues two significant advantages: multi-threaded operation of the common queue does not require additional synchronization, in addition, the queue will automatically balance the load, that is, the other side (production and consumption on both sides) processing faster will be blocked, thereby reducing the processing speed gap on both sides. Here are the specific implementations:


public class Blockingqueuetest {public static void main (string[] args) {Scanner in = new Scanner (system.in          );          System.out.print ("Enter base directory (e.g./usr/local/jdk5.0/src):");          String directory = In.nextline ();          System.out.print ("Enter keyword (e.g. volatile):");            String keyword = in.nextline (); Final int file_queue_size = 10;//block Queue Size final int search_threads = 100;//keyword search thread count//based on Arrayblockin Gqueue blockingqueue<file> queue = new Arrayblockingqueue<file> (file_queue_siz            E); Start only one thread to search the directory Fileenumerationtask enumerator = new Fileenumerationtask (queue, new File (director          y));                    New Thread (Enumerator). Start (); Starts 100 threads used to search the file for the specified keyword for (int i = 1; I <= search_threads; i++) new Thread (New Searchtask (Queu      E, keyword)). Start (); }} class Fileenumerationtask implements Runnable {//Dummy file object, placed at the end of the blocking queue, to indicate that the file has been traversed public static file DUMMY = new file ("");      Private blockingqueue<file> queue;        Private File startingdirectory;          Public Fileenumerationtask (blockingqueue<file> queue, File startingdirectory) {this.queue = queue;      This.startingdirectory = startingdirectory;              } public void Run () {try {enumerate (startingdirectory); Queue.put (DUMMY);//execute here to indicate that the file under the specified directory has been traversed} catch (Interruptedexception e) {}}//Will all the documents under the specified directory The block is placed in the blocking queue as a file object public void enumerate (file directory) throws interruptedexception {file[] files = Direct          Ory.listfiles ();              for (file file:files) {if (File.isdirectory ())) enumerate (file);          else//Put the element in the tail of the queue and block Queue.put (file) if it is full; }}} class Searchtask implements Runnable {private BlockingqueUe<file> queue;        Private String keyword;          Public Searchtask (blockingqueue<file> queue, String keyword) {this.queue = queue;      This.keyword = keyword;              public void Run () {try {boolean-done = false;                  while (!done) {//takes out the first element of the queue, if it is empty, it blocks file File = Queue.take (); if (file = = Fileenumerationtask.dummy) {//is taken out and re-placed so that other threads can read it too quickly to end Queue.put (f                      ILE);                  Done = true;              } else search (file);          }} catch (IOException e) {e.printstacktrace (); } catch (Interruptedexception e) {}} public void search (file file) throws IOException {Scan          NER in = new Scanner (new FileInputStream (file));          int linenumber = 0;              while (In.hasnextline ()) {linenumber++; String Line = In.nextline ();                          if (line.contains (keyword)) System.out.printf ("%s:%d:%s%n", File.getpath (), linenumber,          line);      } in.close ();   }  }


Use of queue in Java

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.