Use of queue queues in Java

Source: Internet
Author: User
Tags sorts

1. In Java5, a new Java.util.Queue interface is added to support the common operation of the queue. The queue interface is the same level as list and set, and both inherit the collection interface.
To avoid collection's add () and remove () methods as much as possible, use the offer () to add elements and use poll () to get and move out of the element. They are excellent
points are determined by the return value, and the Add () and remove () methods throw exceptions when they fail . If you want to use the front end without moving the element, use the
Element () or peek () method.

2. It is noteworthy that the LinkedList class implements the queue interface, so we can use LinkedList as a queue.

3, LinkedList realizes 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.

4, the 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:

   AddAdd a single cable if the queue is full, throw a Iiiegaislabeepeplian exception
RemoveRemove and return elements of the queue header if the queue is empty, throws a Nosuchelementexception exception
elementReturns the element of the queue header if the queue is empty, a Nosuchelementexception exception is thrown
OfferAdds an element and returns true if the queue is full, returns false
PollRemove and return elements to the head of the queue if the queue is empty, NULL is returned
PeekReturns the element of the queue header returns null if the queue is empty
putAdd an element if the queue is full, block
TakeRemove 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.

5, the blocking queue operation can be divided into the following three categories according to their response: AAD, Removee, and element operations throw an exception 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.

6, note: Poll and Peek method error in return null. Therefore, inserting a null value into the queue is not legal.

7.

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 theLinkedblockingqueue 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 a list-based queue, which sorts elements in FIFO (first-in-one-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 extends Comparable<delayed>{  long  getdelay (timeunit unit);        }
View Code

The elements put into delayqueue will also implement the CompareTo method, Delayqueue Use this to sort the elements.

1 Java Code2  Public classBlockingqueuetest {3      Public Static voidMain (string[] args) {4Scanner in =NewScanner (system.in); 5System.out.print ("Enter base directory (e.g./usr/local/jdk5.0/src):"); 6String directory =In.nextline (); 7System.out.print ("Enter keyword (e.g. volatile):"); 8String keyword =In.nextline (); 9   Ten         Final intFile_queue_size = 10;//Block Queue Size One         Final intsearch_threads = 100;//Number of keyword search threads A    -         //Arrayblockingqueue-based blocking queues -blockingqueue<file> queue =NewArrayblockingqueue<file>(   the file_queue_size);  -    -         //start only one thread to search the directory -Fileenumerationtask Enumerator =Newfileenumerationtask (Queue, +                 NewFile (directory));  -         NewThread (Enumerator). Start ();  +            A         //start 100 threads to search for a specified keyword in a file at          for(inti = 1; I <= search_threads; i++)   -             NewThread (Newsearchtask (queue, keyword)). Start ();  -     }   - }   - classFileenumerationtaskImplementsRunnable { -     //dummy file object, placed at the end of the blocking queue, to indicate that the file has been traversed in      Public StaticFile DUMMY =NewFile ("");  -    to     PrivateBlockingqueue<file>queue;  +     PrivateFile startingdirectory;  -    the      PublicFileenumerationtask (blockingqueue<file>queue, File startingdirectory) {   *          This. Queue =queue;  $          This. Startingdirectory =startingdirectory; Panax Notoginseng     }   -    the      Public voidrun () { +         Try {   A Enumerate (startingdirectory);  theQueue.put (DUMMY);//execution to the specified directory where the file has been traversed +}Catch(interruptedexception e) { -         }   $     }   $    -     //places all files under the specified directory into a blocking queue as a file object -      Public voidEnumerate (File directory)throwsinterruptedexception { thefile[] Files =Directory.listfiles ();  -          for(File file:files) {Wuyi             if(File.isdirectory ()) the enumerate (file);  -             Else   Wu                 //put elements in the end of the queue and block if the queues are full - queue.put (file);  About         }   $     }   - }   - classSearchtaskImplementsRunnable { -     PrivateBlockingqueue<file>queue;  A     PrivateString keyword;  +    the      PublicSearchtask (blockingqueue<file>queue, String keyword) {   -          This. Queue =queue;  $          This. Keyword =keyword;  the     }   the    the      Public voidrun () { the         Try {   -             BooleanDone =false;  in              while(!Done ) {   the                 //Remove the first element of the queue and block if it is empty theFile File =Queue.take ();  About                 if(File = =fileenumerationtask.dummy) { the                     //take it out and put it back in so that other threads can read it and end it quickly. the queue.put (file);  theDone =true;  +}Else   - search (file);  the             }  Bayi}Catch(IOException e) { the E.printstacktrace ();  the}Catch(interruptedexception e) { -         }   -     }   the      Public voidSearch (File file)throwsIOException { theScanner in =NewScanner (Newfileinputstream (file));  the         intlinenumber = 0;  the          while(In.hasnextline ()) { -linenumber++;  theString line =In.nextline ();  the             if(line.contains (keyword)) theSystem.out.printf ("%s:%d:%s%n", File.getpath (), linenumber,94 Line );  the         }   the In.close ();  the     }  98}
View Code

Use of queue queues in Java

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.