FileDocCategorySizeDatePackage
SynchronousQueue.javaAPI DocJava SE 6 API43460Tue Jun 10 00:25:56 BST 2008java.util.concurrent

SynchronousQueue

public class SynchronousQueue extends AbstractQueue implements BlockingQueue, Serializable
A {@linkplain BlockingQueue blocking queue} in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one. You cannot peek at a synchronous queue because an element is only present when you try to remove it; you cannot insert an element (using any method) unless another thread is trying to remove it; you cannot iterate as there is nothing to iterate. The head of the queue is the element that the first queued inserting thread is trying to add to the queue; if there is no such queued thread then no element is available for removal and poll() will return null. For purposes of other Collection methods (for example contains), a SynchronousQueue acts as an empty collection. This queue does not permit null elements.

Synchronous queues are similar to rendezvous channels used in CSP and Ada. They are well suited for handoff designs, in which an object running in one thread must sync up with an object running in another thread in order to hand it some information, event, or task.

This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order.

This class and its iterator implement all of the optional methods of the {@link Collection} and {@link Iterator} interfaces.

This class is a member of the Java Collections Framework.

since
1.5
author
Doug Lea and Bill Scherer and Michael Scott
param
the type of elements held in this collection

Fields Summary
private static final long
serialVersionUID
static final int
NCPUS
The number of CPUs, for spin control
static final int
maxTimedSpins
The number of times to spin before blocking in timed waits. The value is empirically derived -- it works well across a variety of processors and OSes. Empirically, the best value seems not to vary with number of CPUs (beyond 2) so is just a constant.
static final int
maxUntimedSpins
The number of times to spin before blocking in untimed waits. This is greater than timed value because untimed waits spin faster since they don't need to check times on each spin.
static final long
spinForTimeoutThreshold
The number of nanoseconds for which it is faster to spin rather than to use timed park. A rough estimate suffices.
private volatile transient Transferer
transferer
The transferer. Set only in constructor, but cannot be declared as final without further complicating serialization. Since this is accessed only at most once per public method, there isn't a noticeable performance penalty for using volatile instead of final here.
private ReentrantLock
qlock
private WaitQueue
waitingProducers
private WaitQueue
waitingConsumers
Constructors Summary
public SynchronousQueue()
Creates a SynchronousQueue with nonfair access policy.

        this(false);
    
public SynchronousQueue(boolean fair)
Creates a SynchronousQueue with the specified fairness policy.

param
fair if true, waiting threads contend in FIFO order for access; otherwise the order is unspecified.

        transferer = (fair)? new TransferQueue() : new TransferStack();
    
Methods Summary
public voidclear()
Does nothing. A SynchronousQueue has no internal capacity.

    
public booleancontains(java.lang.Object o)
Always returns false. A SynchronousQueue has no internal capacity.

param
o the element
return
false

        return false;
    
public booleancontainsAll(java.util.Collection c)
Returns false unless the given collection is empty. A SynchronousQueue has no internal capacity.

param
c the collection
return
false unless given collection is empty

        return c.isEmpty();
    
public intdrainTo(java.util.Collection c)

throws
UnsupportedOperationException {@inheritDoc}
throws
ClassCastException {@inheritDoc}
throws
NullPointerException {@inheritDoc}
throws
IllegalArgumentException {@inheritDoc}

        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        int n = 0;
        E e;
        while ( (e = poll()) != null) {
            c.add(e);
            ++n;
        }
        return n;
    
public intdrainTo(java.util.Collection c, int maxElements)

throws
UnsupportedOperationException {@inheritDoc}
throws
ClassCastException {@inheritDoc}
throws
NullPointerException {@inheritDoc}
throws
IllegalArgumentException {@inheritDoc}

        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        int n = 0;
        E e;
        while (n < maxElements && (e = poll()) != null) {
            c.add(e);
            ++n;
        }
        return n;
    
public booleanisEmpty()
Always returns true. A SynchronousQueue has no internal capacity.

return
true

        return true;
    
public java.util.Iteratoriterator()
Returns an empty iterator in which hasNext always returns false.

return
an empty iterator

        return new EmptyIterator<E>();
    
public booleanoffer(E o, long timeout, java.util.concurrent.TimeUnit unit)
Inserts the specified element into this queue, waiting if necessary up to the specified wait time for another thread to receive it.

return
true if successful, or false if the specified waiting time elapses before a consumer appears.
throws
InterruptedException {@inheritDoc}
throws
NullPointerException {@inheritDoc}

        if (o == null) throw new NullPointerException();
        if (transferer.transfer(o, true, unit.toNanos(timeout)) != null)
            return true;
        if (!Thread.interrupted())
            return false;
        throw new InterruptedException();
    
public booleanoffer(E e)
Inserts the specified element into this queue, if another thread is waiting to receive it.

param
e the element to add
return
true if the element was added to this queue, else false
throws
NullPointerException if the specified element is null

        if (e == null) throw new NullPointerException();
        return transferer.transfer(e, true, 0) != null;
    
public Epeek()
Always returns null. A SynchronousQueue does not return elements unless actively waited on.

return
null

        return null;
    
public Epoll(long timeout, java.util.concurrent.TimeUnit unit)
Retrieves and removes the head of this queue, waiting if necessary up to the specified wait time, for another thread to insert it.

return
the head of this queue, or null if the specified waiting time elapses before an element is present.
throws
InterruptedException {@inheritDoc}

        Object e = transferer.transfer(null, true, unit.toNanos(timeout));
        if (e != null || !Thread.interrupted())
            return (E)e;
        throw new InterruptedException();
    
public Epoll()
Retrieves and removes the head of this queue, if another thread is currently making an element available.

return
the head of this queue, or null if no element is available.

        return (E)transferer.transfer(null, true, 0);
    
public voidput(E o)
Adds the specified element to this queue, waiting if necessary for another thread to receive it.

throws
InterruptedException {@inheritDoc}
throws
NullPointerException {@inheritDoc}

        if (o == null) throw new NullPointerException();
        if (transferer.transfer(o, false, 0) == null) {
	    Thread.interrupted();
            throw new InterruptedException();
	}
    
private voidreadObject(java.io.ObjectInputStream s)

        s.defaultReadObject();
        if (waitingProducers instanceof FifoWaitQueue)
            transferer = new TransferQueue();
        else
            transferer = new TransferStack();
    
public intremainingCapacity()
Always returns zero. A SynchronousQueue has no internal capacity.

return
zero.

        return 0;
    
public booleanremove(java.lang.Object o)
Always returns false. A SynchronousQueue has no internal capacity.

param
o the element to remove
return
false

        return false;
    
public booleanremoveAll(java.util.Collection c)
Always returns false. A SynchronousQueue has no internal capacity.

param
c the collection
return
false

        return false;
    
public booleanretainAll(java.util.Collection c)
Always returns false. A SynchronousQueue has no internal capacity.

param
c the collection
return
false

        return false;
    
public intsize()
Always returns zero. A SynchronousQueue has no internal capacity.

return
zero.

        return 0;
    
public Etake()
Retrieves and removes the head of this queue, waiting if necessary for another thread to insert it.

return
the head of this queue
throws
InterruptedException {@inheritDoc}

        Object e = transferer.transfer(null, false, 0);
        if (e != null)
            return (E)e;
	Thread.interrupted();
        throw new InterruptedException();
    
public java.lang.Object[]toArray()
Returns a zero-length array.

return
a zero-length array

        return new Object[0];
    
public T[]toArray(T[] a)
Sets the zeroeth element of the specified array to null (if the array has non-zero length) and returns it.

param
a the array
return
the specified array
throws
NullPointerException if the specified array is null

        if (a.length > 0)
            a[0] = null;
        return a;
    
private voidwriteObject(java.io.ObjectOutputStream s)
Save the state to a stream (that is, serialize it).

param
s the stream


                       
       
          
        boolean fair = transferer instanceof TransferQueue;
        if (fair) {
            qlock = new ReentrantLock(true);
            waitingProducers = new FifoWaitQueue();
            waitingConsumers = new FifoWaitQueue();
        }
        else {
            qlock = new ReentrantLock();
            waitingProducers = new LifoWaitQueue();
            waitingConsumers = new LifoWaitQueue();
        }
        s.defaultWriteObject();