In the early stages of Java programming, a professor at SUNY, New York State University in oswego, decided to create a simple library, to help developers build applications that can better handle multithreading. This does not mean that it cannot be implemented with an existing library, but just like with a standard network library, it is easier to process multithreading with a debugged and trustable library. With the help of a book related to addision-Wesley, this library has become increasingly popular. Finally, Doug Lea decided to try to make it a standard part of the Java platform-JSR-166. This library is changed to the tiger version.
java.util.concurrentPackage. In this newTaming TigerIn the tip, we will explore the new
QueueInterface, non-concurrent and concurrent implementation of this interface, concurrencyMapImplementation and dedicated read operations are much more concurrent than write operations.
ListAndSet.
Introduction to the queue Interface
java.utilThe package provides a new basic interface for the Collection:java.util.Queue. Although it is certainly possible to add and delete the corresponding two ends
java.util.ListAs a queue, but this newQueueThe interface provides more methods to add, delete, and check a set, as shown below:
public boolean offer(Object element)public Object remove()public Object poll()public Object element()public Object peek()
Basically, a queue is a first-in-first-out (FIFO) data structure. Some queues have size restrictions. Therefore, if you want to add a new item to a full queue, the extra items will be rejected. This time new
offerMethod. It is not for callingadd()The method throws an unchecked exception, but only obtains
offer()Returns false.remove()Andpoll()Methods are used to delete the first element (head) from the queue ).
remove()Behavior andCollectionThe API version is similar, but the newpoll()The method does not throw an exception when calling an empty set, but returns NULL. Therefore, the new method is more suitable for situations that are prone to abnormal conditions. The last two methods
element()Andpeek()Used to query elements in the queue header. Andremove()The method is similar. When the queue is empty,
element()Throw an exception whilepeek()Returns null.
Use Basic queue
There are two groups in TigerQueueImplementation: implements a newBlockingQueueAnd does not implement this interface. I will first analyze the unimplemented ones.
In the simplest case, the originaljava.util.LinkedListImplementation has been transformed into not only implementationjava.util.ListAnd implements
java.util.QueueInterface. The set can be regarded as either of the two. Listing 1 showsLinkedListAs
QueueOne method used:
Listing 1. Using queue
Queue queue = new LinkedList(); queue.offer("One"); queue.offer("Two"); queue.offer("Three"); queue.offer("Four"); // Head of queue should be One System.out.println("Head of queue is: " + queue.poll());
What's more complicated is the newjava.util.AbstractQueueClass. This class works in a way similarjava.util.AbstractListAnd
java.util.AbstractSetClass. When creating a custom set, you do not need to implement the entire interface by yourself, but inherit the abstract implementation and fill in the details. Use
AbstractQueueMust be a methodoffer(),poll()Andpeek()Provides implementation. Image
add()AndaddAll()This method is modified to useoffer(), And
clear()Andremove()Usepoll(). Finally,element()Use
peek(). Of course, the optimization implementation of these methods can be provided in the subclass, but this is not necessary. Besides, you do not need to create your own subclass. You can use several built-in implementations. Two of them are non-blocking Queues:
PriorityQueueAndConcurrentLinkedQueue.
PriorityQueueAndConcurrentLinkedQueueClass adds two specific set implementations to the Collection framework.
PriorityQueueThe class essentially maintains an ordered list. AddQueueElements in
java.util.ComparableImplemented) or according tojava.util.ComparatorImplementation. Set
LinkedListChangedPriorityQueueThe four instead of one will be printed, because the strings are listed in alphabetical order-the four is the first one.
ConcurrentLinkedQueueIt is a thread-safe Queue Based on Link nodes. Concurrent access does not need to be synchronized. Because it adds elements to the end of the queue and deletes them from the header, as long as you do not need to know the queue size,
ConcurrentLinkedQueueShared access to public sets can work well. It is slow to collect information about the queue size. You need to traverse the queue.
Use blocking queue
Newjava.util.concurrentThe package is added to the specific collection classes available in the Collection framework.
BlockingQueueInterface and five blocking queue classes. If you are not familiar with the concept of blocking queues, it is essentially a one-bit distorted FIFO data structure. The thread does not immediately add or delete elements from the queue, and the operations are blocked until space or elements are available.
BlockingQueueThe javadoc of the interface provides the basic usage of blocking queues, as shown in Listing 2. In the producerput()The Operation will block when there is no space available, and the consumer's
take()The operation will be blocked when there is nothing in the queue.
Listing 2. Using blockingqueue
class Producer implements Runnable { private final BlockingQueue queue; Producer(BlockingQueue q) { queue = q; } public void run() { try { while(true) { queue.put(produce()); } } catch (InterruptedException ex) { ... handle ...} } Object produce() { ... } } class Consumer implements Runnable { private final BlockingQueue queue; Consumer(BlockingQueue q) { queue = q; } public void run() { try { while(true) { consume(queue.take()); } } catch (InterruptedException ex) { ... handle ...} } void consume(Object x) { ... } } class Setup { void main() { BlockingQueue q = new SomeQueueImplementation(); Producer p = new Producer(q); Consumer c1 = new Consumer(q); Consumer c2 = new Consumer(q); new Thread(p).start(); new Thread(c1).start(); new Thread(c2).start(); } }
The five queues provide different functions:
ArrayBlockingQueue: A Bounded queue supported by arrays.
LinkedBlockingQueue: An optional bounded queue supported by a linked node.
PriorityBlockingQueue: An unbounded priority queue supported by the priority heap.
DelayQueue: A time-based scheduling queue supported by the priority heap.
SynchronousQueue: One ExploitationBlockingQueueInterface's simple aggregation mechanism.
First two classesArrayBlockingQueueAndLinkedBlockingQueueThey are almost the same, but they are different in terms of backup storage,
LinkedBlockingQueueThere is not always a limit on capacity. No size limitLinkedBlockingQueueWhen adding elements to a class, there will never be a wait for blocking the queue (at least there is
Integer.MAX_VALUENot before the element ).
PriorityBlockingQueueIs a queue with unlimited capacity, which uses the contained elementsComparableSort order to maintain elements in a logical order. It can be viewed
TreeSet. For example, adding strings one, two, three, and four to the queue will cause the four to be obtained by the first one. For elements that do not have a natural order, you can provide
Comparator. HoweverPriorityBlockingQueueThere is a skill. Slaveiterator()Returned
IteratorThe instance does not need to return elements in priority order. If all elements must be traversed in the order of prioritytoArray()Method and sort them by yourself, like
Arrays.sort(pq.toArray()).
NewDelayQueueImplementation may be one of the most interesting (and complex. New elements must be added to the queue.DelayedInterface (only one method --
long getDelay(java.util.concurrent.TimeUnit unit)). Because there is no limit on the queue size, the addition can return immediately, but the elements cannot be retrieved from the queue before the delay time expires. If multiple elements are delayed, the first element with the longest expiration time is removed. In fact, it does not sound so complicated. Listing 3 demonstrates the use of this new set of blocking Queues:
Listing 3. Using delayqueue
import java.util.*;import java.util.concurrent.*;public class Delay { /** * Delayed implementation that actually delays */ static class NanoDelay implements Delayed { long trigger; NanoDelay(long i) { trigger = System.nanoTime() + i; } public int compareTo(Object y) { long i = trigger; long j = ((NanoDelay)y).trigger; if (i < j) return -1; if (i > j) return 1; return 0; } public boolean equals(Object other) { return ((NanoDelay)other).trigger == trigger; } public boolean equals(NanoDelay other) { return ((NanoDelay)other).trigger == trigger; } public long getDelay(TimeUnit unit) { long n = trigger - System.nanoTime(); return unit.convert(n, TimeUnit.NANOSECONDS); } public long getTriggerTime() { return trigger; } public String toString() { return String.valueOf(trigger); } } public static void main(String args[]) throws InterruptedException { Random random = new Random(); DelayQueue queue = new DelayQueue(); for (int i=0; i < 5; i++) { queue.add(new NanoDelay(random.nextInt(1000))); } long last = 0; for (int i=0; i < 5; i++) { NanoDelay delay = (NanoDelay)(queue.take()); long tt = delay.getTriggerTime(); System.out.println("Trigger time: " + tt); if (i != 0) { System.out.println("Delta: " + (tt - last)); } last = tt; } }}
This example is an internal classNanoDelayIt will suspend any number of nanosecond in essence.SystemNew
nanoTime()Method. Thenmain()The method isNanoDelayObjects are placed in the queue and retrieved again. If you want the queue items to do something else, you need
DelayedAdd a method to the implementation of the object, and call this new method after extracting it from the queue. (Expand at will.NanoDelayTo experiment with other methods to do something interesting .) Shows the time difference between two calls to retrieve elements from the queue. If the time difference is negative, it can be regarded as an error because it will never get an item from the queue at an earlier trigger time after the delay time ends.
SynchronousQueueClass is the simplest. It has no internal capacity. It is like a hand-delivery mechanism between threads. The producer that adds an element to the queue will wait for the consumer of another thread. When this consumer appears, this element is directly transmitted between the consumer and the producer and will never be added to the blocking queue.
Use concurrentmap
Newjava.util.concurrent.ConcurrentMapInterfaces andConcurrentHashMapThe implementation can only add an element to the map when the key does not exist. Only when the key exists and maps to a specific value can an element be deleted from the map.
There is a newputIfAbsent()Method is used to add in map. This method to addConcurrentMapThe key value in the implementation is a parameter, just like the normal
put()Method, but only when the map does not contain this key can the key be added to the map. If map already contains this key, the existing value of this key will be retained.
putIfAbsent()The method is atomic. If you do not call this atomic operation, you need to call the code in Listing 4 from the appropriate synchronization block:
Listing 4. Equivalent putifabsent () Code
if (!map.containsKey(key)) { return map.put(key, value); } else { return map.get(key); }
Use copyonwritearraylist and copyonwritearrayset
In Doug Lea'sConcurrent Programming in JavaChapter 2 2.4.4 of the book (see
Reference), the best description of the copy-on-write mode. Essentially, this pattern declares that, to maintain consistent object snapshots, immutability is required to eliminate synchronization required for coordinated reading of different but related attributes. For a set, this means that if there is a large number of reads (that is
get()) And iteration, do not need to synchronize operations to take care of occasional writes (that isadd(). For newCopyOnWriteArrayListAnd
CopyOnWriteArraySetClass, all mutable operations first get a copy of the background array, change the copy, and then replace the copy. This method ensures that it will never throw
ConcurrentModificationException. Traversing a set will be completed with the original set, and using the updated Set in future operations.
These new sets,CopyOnWriteArrayListAndCopyOnWriteArraySetWhich is most suitable for read operations that generally exceed write operations. The most common example is to use the listener list. As we have already said, the swing component has not been changed to a new set. Instead, they continue to use
javax.swing.event.EventListenerListTo maintain their listener list.
As shown in Listing 6, the use of collections is exactly the same as their non-copy-on-write alternatives. Only create a set and add or delete elements in it. Even if the object is added to the collection, the original
IteratorYou can also continue to traverse the items in the original set.
Listing 6. A copy-on-write set is displayed.
import java.util.*;import java.util.concurrent.*;public class CopyOnWrite { public static void main(String args[]) { List list1 = new CopyOnWriteArrayList(Arrays.asList(args)); List list2 = new ArrayList(Arrays.asList(args)); Iterator itor1 = list1.iterator(); Iterator itor2 = list2.iterator(); list1.add("New"); list2.add("New"); try { printAll(itor1); } catch (ConcurrentModificationException e) { System.err.println("Shouldn't get here"); } try { printAll(itor2); } catch (ConcurrentModificationException e) { System.err.println("Will get here."); } } private static void printAll(Iterator itor) { while (itor.hasNext()) { System.out.println(itor.next()); } }}
This example program is created with command line parametersCopyOnWriteArrayListAndArrayListThese two instances. In
IteratorAnd then add an element to it. WhenArrayListIteration is caused by oneConcurrentModificationExceptionWhen the problem stops immediately,
CopyOnWriteArrayListThe iteration can continue without throwing an exception, because the original set changes after the iterator is obtained. If this behavior (such as notifying all elements in the original event listener) is required, you 'd better use the copy-on-write set. If it is not used, the original one will be used and it will be processed in case of exceptions.
Conclusion
There are many important additions in the tiger version of j2se platform. In addition to changes in the language level, such as general support, this library may be the most important increase because it will be used by the widest range of users. Do not ignore other packages added to the platform, such as Java Management Extensions (JMX). However, most other important library enhancements are only for developers with narrow scopes. But this database is not. In addition to other concurrent utilities used for locking and atomic operations, these classes are also frequently used. Learn about them as early as possible and take advantage of the features they provide.
Address: http://www.ibm.com/developerworks/cn/java/j-tiger06164/#main