Follow queue: Java 1.5 adds a new data structure Interface

Source: Internet
Author: User

Follow queue: Java 1.5 adds a new data structure Interface

Java 1.5 provides internal support for queue, one of the most basic data structures in programming. This article will explore the queue interface added to the java. util package and demonstrate how to use this new feature to stream your data processing.

By kulvir Singh bhogal (Translated by Victor Jan 2004-09-26)
See http://www.devx.com/Java/Article/21983/1954? PF = true)

In computer science, one of the basic data structures is queue. You will remember that queue is a data structure in which elements can be removed in the same order as they are added. In earlier Java versions, the FIFO (first-in-first-out) data structure is unfortunately ignored. With the emergence of java1.5 (also known as Tiger), the Support for queue has become an inherent feature for the first time.

In the past, how did I manage a queue without a queue?

Before Java 1.5, the common implementation method is to use the java. util. List set to imitate queue. The concept of queue is to add an object (called the enqueuing operation) to the end of the list (that is, the back of the queue) and) extract an object and remove it from the list (called the dequeuing operation) to simulate it. The following code shows your previous practices.

import java.util.Enumeration;import java.util.LinkedList;import java.util.Vector;public class QueueEmulate {     private LinkedList queueMembers;     public Object enqueue(Object element)     {          queueMembers.add (element);          return element;     }     public Object dequeue()      {          return queueMembers.removeFirst();     }}

Now we have queue

Java 1.5 adds the queue interface in the Java. util package. The following code uses it (captured from simplequeueusageexample. Java of sample code ). Note: In Java 1.5, java. util. Queue list is used to implement java. util. queue, Just Like java. util. List interface. Also note how I explicitly declare my queue that only contains strings --- use the <string> generic type (for more information about generics, see "j2se 1.5: java's evolution continues "). This makes it difficult for us to shape objects when extracting them from queue.

Queue<String> myQueue = new LinkedList<String>();myQueue.add("Add Me");myQueue.add("Add Me Too");String enqueued = myQueue.remove();

You can see that the add and remove methods of the sort list class are used to perform the enqueuing and dequeuing Operations respectively. There are actually no better available methods; the queue interface provides new offer and poll methods, as shown below (captured from simplequeueusageexamplepreferred ):

Queue<String> myQueue = new LinkedList<String>();boolean offerSuccess;// offer method tries to enqueue.  // A boolean is returned telling you if the // attempt to add to the queue was successful or notofferSuccess=myQueue.offer("Add Me");offerSuccess=myQueue.offer("Add Me Too");// peek at the head of the queue, but don't grab itObject pull = myQueue.peek();String enqueued = null;// grab the head of the queueif (pull!=null) enqueued = myQueue.poll();System.out.println(enqueued);

If your queue has a fixed length limit (this is often the case), using the add method to add content to the queue will throw a non-check exception. When you compile simplequeueusageexample code, the compiler will issue a warning. On the contrary, if the new offer method tries to be added, true is returned if everything is normal. Otherwise, false is returned. Similarly, if you try to use the Remove Method to operate on an empty queue, it will also cause a non-check exception.

You can also use the poll method to extract elements from the queue. If no element exists in the queue, the poll method returns a null value (that is, no exception is thrown ). In some cases, you may not want to extract the elements in the header, but just want to take a look. The queue interface provides a peek method to do this. If you are processing an empty queue, the peek method returns NULL. Like the add-offer and remove-poll relationships, there is also a peek-element relationship. When the queue is empty, the element method throws a non-check exception. However, if there is an element in the queue, the peek method allows you to view the first element without actually extracting it from the queue. The usage of the peek method is shown in the simplequeueusageexamplepreferred class.

 

Abstractqueue class

As you can see, the Java. util. shortlist class implements the java. util. Queue interface. Likewise, the same is true for abstractqueue. The abstractqueue class implements some methods of the Java. util interface (so its name contains abstract ). Abstractqueue focuses on implementing offer, poll, and peek methods. In addition, some specific implementations are used.

Priorityqueue class

In priorityqueue, when you add elements to the queue, automatic sorting is implemented. Based on the different constructors of the priorityqueue you use, the order of the queue elements is determined either based on their natural order or through the comparator passed in by the priorirtyqueue constructor. The following code demonstrates how to use the pirorityqueue class. The front side of the queue is the string "Alabama"-because the elements are arranged in the natural order in priorityqueue (in this example, they are in alphabetical order ).

PriorityQueue<String> priorityQueue = new PriorityQueue<String>();priorityQueue.offer("Texas");priorityQueue.offer("Alabama");priorityQueue.offer("California");priorityQueue.offer("Rhode Island");int queueSize = priorityQueue.size();for (int i =0; i< queueSize; i++){     System.out.println(priorityQueue.poll());}

The execution result is as follows:

AlabamaCaliforniaRhode IslandTexas


Queue items are arranged in alphabetical order.

As mentioned above, you can create your own comparator class and provide it to pirorityqueue. In this way, you can define your own sorting method. This method can be found in the priorityqueuecomparatorusageexample class, where a helper class named state is used. As you can see below, in the class definition, State only contains a name and population.

private String name;private int population;public State(String name, int population){     super();     this.name = name;     this.population = population;}public String getName(){     return this.name;}public int getPopulation(){     return this.population;}public String toString(){     return getName() + " - " + getPopulation();}

In priorityqueuecomparatorusageexample, queue uses the custom implementation of Java. util. comparator to define the order (as follows ).

PriorityQueue<State> priorityQueue =      new PriorityQueue(6, new Comparator<State>(){     public int compare(State a, State b)     {       System.out.println("Comparing Populations");       int populationA = a.getPopulation();       int populationB = b.getPopulation();       if (populationB>populationA)            return 1;       else if (populationB<populationA)            return -1;       else             return 0;      }});

After executing the priorityqueuecomparatorusageexample class, the State object added to the queue will be discharged by population (from low to high ).

 

Blocking queue

Queue is usually limited to a given size. So far, you have seen through the queue implementation that the use of offer or add method enqueue Queue (dequeue queue with remove or poll) is assumed that if the queue cannot provide the add or remove operation, you do not need to wait for the program to run. Java. util. Concurrent. blockingqueue interface blocking. It adds the put and take methods. An example may be more useful.

Use the original producer/consumer relationship to assume that your producer writes a queue (more specifically a blockingqueue ). You have some consumers that are reading from the queue. In an ordered mode, which method do you want to see. Basically, each consumer needs to wait before it and be authorized to extract the previous consumer of the project from the queue. Using a program to construct this structure, a producer thread is used to write data to a queue, and then some consumer threads are generated to read data from the same queue. Note that the thread will block another thread until the current thread finishes extracting an item from the queue.

The following code shows the process of writing blockingqueue by producer. Note that the objects in the run method (you have the responsibility to implement them because you inherit the thread) are put into blockingqueue after waiting for a random amount of time (ranging from 100 to 500 milliseconds. Objects placed in the queue are only strings containing the time when the message was generated.

The actual work of adding an object is implemented by the following statement:
blockingQueue.put("Enqueued at: " + time)

The put method throws interruptedexception. Therefore, the put operation must be surrounded by try... catch blocks to capture thrown exceptions (see Listing 1 ).

The consumer object is extracted from the producer. It also inherits from the thread object and therefore implements the run method (see Listing 2 ).

The consumer class is designed to be similar to the producer class. The consumer class uses the take method to retrieve (dequeue) messages from the queue, rather than placing the messages in blockingqueue. As mentioned above, this takes place only when something exists in the queue. If the producer thread stops placing (enqueue) objects in the queue, the consumer will wait until the queue project is valid. The testblockingqueue class shown below generates four consumer threads that try to extract objects from blockingqueue.

import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;public class TestBlockingQueue{  public static void main(String args[])  {    BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>();    Producer producer = new Producer(blockingQueue, System.out);    Consumer consumerA = new Consumer("ConsumerA", blockingQueue, System.out);    Consumer consumerB = new Consumer("ConsumerB", blockingQueue, System.out);    Consumer consumerC = new Consumer("ConsumerC", blockingQueue, System.out);    Consumer consumerD = new Consumer("ConsumerD", blockingQueue, System.out);    producer.start();    consumerA.start();    consumerB.start();    consumerC.start();    consumerD.start();    }}
 
Figure 1.Consumer threads:These threads dequeue messages fromBlockingqueueIn the order that you spawned them.

The following line creates blockingqueue:

BlockingQueue<String> blockingQueue 
                    = new LinkedBlockingQueue<String>();

Note that it is implemented using blockingqueue's linkedblockingqueue. This is because blockingqueue is an abstract class and you cannot instantiate it directly. You can also use the arrayblockingqueuequeue type. Arrayblockingqueue uses an array as its storage device, while linkedblockingqueue uses an array list. The capacity of arrayblockingqueue is fixed. For linkedblockingqueue, the maximum value can be specified. The default value is borderless. This example uses the borderless method.

During the execution of the class, read objects from the queue and execute them in sequence (see the execution in the following example ). In fact, a consumer thread blocks other threads that access blockingqueue until it can retrieve an object from the queue.

 

Delayqueue-I am/not complete

In some cases, objects stored in the queue need to be placed in another queue for a period of time before they are ready to be taken out. You can use the java. util. Concurrent. delayqueue class to implement the blockingqueue interface. Delayqueue requires that the queue object be resident on the queue for a specified period of time.

The real example I want to use to prove it (which may be what you're eager for) is about muffins ). Oh, Muffin object (like the Java we are talking about-there is no intention of coffee double-off ). Suppose you have a delayqueue and put some muffin objects in it. The Muffin object (as shown below) must implement the java. util. Concurrent. Delayed interface so that it can be placed in delayqueue. This interface requires the muffin object to implement the getdelay method (as shown below ). The getdelay method actually declares how long the object will be stored in delayqueue. When the value returned by this method is 0 or less than 0, the object is ready (or in this example, It is baked) and can be retrieved (see listing 3 ).

The Muffin class also implements the compareto (Java. util. Concurrent. Delayed) method. Because the delayed interface inherits from the java. Lang. Comparable class, this Convention restricts the bakecompletion time of the muffin object.

Because you don't really want to eat not fully baked muffin, you need to store the recommended baking time in delayqueue. Listing 4, taken from the delayqueueusageexample class, shows the enqueue and dequeue muffin objects from delayqueue.

As you can see, the baking time for the muffin object is set using its constructor (the constructor expects the baking time to be in seconds ).

As mentioned above, a muffin object is not allowed to be taken out in delayqueue until its delay time (also called baking time) expires. The element is extracted from the queue based on the earliest delay time. In this example, if you have some muffin objects that have been baked, they will be taken out based on how long they have waited (in other words, the earliest muffin will be taken out before the newly baked muffin ).

Synchronousqueue

In Java 1.5, another way to block the queue is synchronousqueue. Interestingly, this queue has no internal capacity. This is intentional, because queue is intended to be used for delivery purposes. This means that in a synchronous queue structure, the put request must wait for the take request from another thread to synchronousqueue. At the same time, a take request must wait for a put request from another thread to synchronousqueue. Use a program to sample this concept. For more information, see sample code. Similar to the forward blockingqueue example, it contains a consumer (synchconsumer), see listing 5.

The code in listing 5 uses the poll (long timeout, timeunit unit) method of the synchronousqueue class. This method allows the poll process to wait for a specified time (in this example, 20 seconds) Before waiting for another consumption thread to write synchronousqueue ).

In Listing 6, the producer (synchproducer) uses similar offer (e o, long timeout, timeunit unit) Methods to place objects in synchronousqueue. This method allows you to wait for a while before waiting for another thread to read synchronousqueue (in this example, 10 seconds ).

Testsynchqueue shows the actions of producer and consumer:

import java.util.concurrent.SynchronousQueue;import java.util.concurrent.LinkedBlockingQueue;public class TestSynchQueue{  public static void main(String args[])  {    SynchronousQueue<String> synchQueue = new SynchronousQueue<String>();    SynchProducer producer = new SynchProducer("ProducerA",synchQueue, System.out);    SynchConsumer consumerA = new SynchConsumer("ConsumerA", synchQueue, System.out);    consumerA.start();    producer.start();  }}

When trying to understand the concept behind synchronousqueue, remember where these queue are usually used. The synchronized queue in javadoc indicates:

"They [synchronize queue] are suitable for the transfer design, where objects running in one thread must be synchronized with objects running in another thread so that they can be handed over to some information, time, or task. "

Author profile:

Kulvir Singh bhogal is a consultant for IBM who plans and implements a Java-centric solution on the customer's website.

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.