JDK7 has enhanced the j.u.c concurrency tool in JDK5, one of which is the addition of Transferqueue. Java concurrency-related JSR specification allows you to view the blogs maintained by Doug Lea. Now let's briefly describe how this class is used.
Public interface transferqueue<e> extends blockingqueue<e>{/** * Transfers the element to a waiting co Nsumer immediately, if possible. * * <p>more precisely, transfers the specified element immediately * if there exists a consumer already wait ing to receive it (in * {@link #take} or timed {@link #poll (long,timeunit) poll}), * Otherwise returning {@code FA LSE} without enqueuing the element. * * @param e the element to transfer * @return {@code true} if the element is transferred, else * {@c Ode false} * @throws ClassCastException if the class of the specified element * prevents it from being add Ed to this queue * @throws NullPointerException If the specified element is null * @throws Illegalargumentexceptio N If some property of the specified * element prevents it from being added to this queue */Boolean try Transfer (e e); /** * Transfers the element to a consumer, waiting if necessary to does so. * * <p>more precisely, transfers the specified element immediately * if there exists a consumer already wait ing to receive it (in * {@link #take} or timed {@link #poll (long,timeunit) poll}), * Else waits until the element is received by a consumer. * * @param e the element to transfer * @throws interruptedexception if interrupted and waiting, * in Which case the element isn't left enqueued * @throws classcastexception if the class of the specified element * Prevents it from being added to this queue * @throws NullPointerException If the specified element is null * @throws IllegalArgumentException If some property of the specified * element prevents it from being added T o this queue */void transfer (E e) throws interruptedexception; /** * Transfers the element to a consumer if it was possible to doing so * before the timeout elapses. * * <p>more Precisely, transfers the specified element immediately * if there exists a consumer already waiting to receive it * {@link #take} or timed {@link #poll (long,timeunit) poll}), * Else waits until the element is received by a cons Umer, * Returning {@code false} if the specified wait time elapses * Before the element can be transferred. * * @param e the element to transfer * @param timeout how long to wait before giving up, in units of * {@code Unit} * @param unit a {@code timeunit} determining how to interpret the * {@code timeout} parameter * @return {@code true} if successful, or {@code false} if * The specified waiting time elapses before comp Letion, * in which case the element was not left enqueued * @throws interruptedexception if interrupted whi Le waiting, * in which case the element was not left enqueued * @throws classcastexception if the class of The specified element* Prevents it from being added to this queue * @throws NullPointerException If the specified element is null * @throws IllegalArgumentException If some property of the specified * element prevents it from being added To this queue */Boolean Trytransfer (e E, long timeout, timeunit unit) throws Interruptedexception; /** * Returns {@code true} if there is at least one consumer waiting * to receive a element via {@link #take} or * Timed {@link #poll (long,timeunit) poll}. * The return value represents a momentary state of affairs. * * @return {@code true} if there is at least one waiting consumer */Boolean haswaitingconsumer (); /** * Returns An estimate of the number of consumers waiting to * receive elements via {@link #take} or timed * {@link #poll (long,timeunit) poll}. The return value is an * approximation of a momentary state of affairs, which may be * inaccurate if consumers has CompLeted or given up waiting. * The value of May is useful for monitoring and heuristics, but * not for synchronization control. Implementations of this * method is likely to being noticeably slower than those for * {@link #hasWaitingConsumer}. * * @return The number of consumers waiting to receive elements */int getwaitingconsumercount ();}
You can see that Transferqueue is also a blocking queue, which has all the features of the blocking queue, mainly introduces the role of the above 5 new APIs.
1.transfer (e) If a consumer thread is currently waiting to be acquired, the E is immediately handed over; otherwise, the element e is inserted at the end of the queue, and the current thread goes into a blocking state until a consumer thread takes the element away.
public class Transferqueuedemo {private static transferqueue<string> queue = new linkedtransferqueue<string > ();p ublic static void Main (string[] args) throws Exception {new Productor (1). Start (); Thread.Sleep (100); System.out.println ("over.size=" + queue.size ());} Static Class Productor extends Thread {private int id;public productor (int id) {this.id = ID;} @Overridepublic void Run () {try {String result = "id=" + this.id; SYSTEM.OUT.PRINTLN ("Begin to produce." + result); Queue.transfer (result); System.out.println ("Success to produce." + result); catch (Interruptedexception e) {e.printstacktrace ();}}}}
you can see that the producer thread is blocking because no consumer is waiting to get the data when calling transfer (). The queue length becomes 1, indicating that element e is inserted at the end of the blocking queue when it is not successfully handed over.
2.tryTransfer (e) If there is currently a consumer thread waiting to be acquired, the method will immediately transfer E and return True, or false if it does not, but will not insert E into the queue. This method does not block the current thread, either quickly returns true, or quickly returns false.
3.hasWaitingConsumer () and Getwaitingconsumercount () are used to determine the number of consumer threads currently waiting to be consumed.
4.tryTransfer (e E, long timeout, timeunit unit) If there is currently a consumer thread waiting to be acquired, it will be transferred to it immediately; Otherwise, the element e is inserted at the end of the queue and waits for consumption by the consumer thread. If the element e cannot be fetched by the consumer thread for the specified time, then false is returned, and the element is removed from the queue.
public class Transferqueuedemo {private static transferqueue<string> queue = new linkedtransferqueue<string > ();p ublic static void Main (string[] args) throws Exception {new Productor (1). Start (); Thread.Sleep (100); System.out.println ("over.size=" + queue.size ());//1thread.sleep (1500); System.out.println ("over.size=" + queue.size ())//0}static class Productor extends Thread {private int id;public Productor (int id) {this.id = ID;} @Overridepublic void Run () {try {String result = "id=" + this.id; SYSTEM.OUT.PRINTLN ("Begin to produce." + result); Queue.trytransfer (result, 1, timeunit.seconds); System.out.println ("Success to produce." + result); catch (Exception e) {e.printstacktrace ();}}}}
The first time has not reached the specified time, the element is inserted into the queue, all queue Length is 1, the second specified time slice is exhausted, the element is removed from the queue, so the queue length is 0.
This article describes how Synchronousqueue is used, and you can see that transferqueue also has all the features of Synchronousqueue, but Transferqueue is more powerful. The differences between the 2 APIs are mentioned in this article:
Transferqueue is more generic and useful than synchronousqueue However as it allows your to flexibly decide whether Normal Blockingqueue semantics or a guaranteed hand-off. In the case where items is already in the queue, calling transfer would guarantee that all existing queue items would be PR Ocessed before the transferred item. Synchronousqueue implementation uses dual queues (for waiting producers and waiting consumers) and protects both queues WI Th a single lock. The LinkedTransferQueue implementation uses CAS operations to form a nonblocking implementation and that's at the Heart O F Avoiding serialization bottlenecks.
The use of Transferqueue in JDK7 and the difference between Transferqueue and Synchronousqueue