Top Description Inners Fields Constructors Methods
java.util.concurrent

public Class SynchronousQueue<E>

extends AbstractQueue<E>
implements BlockingQueue<E>, Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable, java.util.concurrent.BlockingQueue, java.util.Queue, java.util.Collection, java.lang.Iterable
Type Parameters
<E>
the type of elements held in this queue
Imports
java.lang.invoke.MethodHandles, .VarHandle, java.util.AbstractQueue, .Collection, .Collections, .Iterator, .Objects, .Spliterator, .Spliterators, java.util.concurrent.locks.LockSupport, .ReentrantLock, java.util.concurrent.ForkJoinWorkerThread, .LinkedTransferQueue, .TransferQueue

A 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 Collection and Iterator interfaces.

This class is a member of the Java Collections Framework.

Author
Doug Lea and Bill Scherer and Michael Scott
Since
1.5

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
pack-priv static class
pack-priv static class
SynchronousQueue.Transferer<E>

Extension of LinkedTransferQueue to support Lifo (stack) mode.

pack-priv static class

Field Summary

Modifier and TypeField and Description
private final transient boolean
private ReentrantLock
private static final long
private final transient SynchronousQueue.Transferer<E>
transferer

The transferer.

private SynchronousQueue.WaitQueue
private SynchronousQueue.WaitQueue

Constructor Summary

AccessConstructor and Description
public
SynchronousQueue()

Creates a SynchronousQueue with nonfair access policy.

public
SynchronousQueue(boolean
if true, waiting threads contend in FIFO order for access; otherwise the order is unspecified.
fair
)

Creates a SynchronousQueue with the specified fairness policy.

Method Summary

Modifier and TypeMethod and Description
public void
clear()

Overrides java.util.AbstractQueue.clear.

Implements java.util.Collection.clear.

Does nothing.

public boolean
public boolean

Returns:

false unless given collection is empty
containsAll
(Collection<?>
the collection
c
)

Overrides java.util.AbstractCollection.containsAll.

Implements java.util.Collection.containsAll.

Returns false unless the given collection is empty.

public int
drainTo(Collection<? super E>
the collection to transfer elements into
c
)

Implements java.util.concurrent.BlockingQueue.drainTo.

Removes all available elements from this queue and adds them to the given collection.

public int
drainTo(Collection<? super E>
the collection to transfer elements into
c
,
int
the maximum number of elements to transfer
maxElements
)

Implements java.util.concurrent.BlockingQueue.drainTo.

Removes at most the given number of available elements from this queue and adds them to the given collection.

public boolean

Returns:

true
isEmpty
()

Overrides java.util.AbstractCollection.isEmpty.

Implements java.util.Collection.isEmpty.

Always returns true.

public Iterator<E>

Returns:

an empty iterator
iterator
()

Implements abstract java.util.AbstractCollection.iterator.

Implements java.util.Collection.iterator.

Returns an empty iterator in which hasNext always returns false.

public boolean

Returns:

true if successful, or false if the specified waiting time elapses before a consumer appears
offer
(E
the element to add
e
,
long
how long to wait before giving up, in units of unit
timeout
,
TimeUnit
a TimeUnit determining how to interpret the timeout parameter
unit
)

Implements java.util.concurrent.BlockingQueue.offer.

Inserts the specified element into this queue, waiting if necessary up to the specified wait time for another thread to receive it.

public boolean

Returns:

true if the element was added to this queue, else false
offer
(E
the element to add
e
)

Implements java.util.concurrent.BlockingQueue.offer, java.util.Queue.offer.

Inserts the specified element into this queue, if another thread is waiting to receive it.

public E

Returns:

null
peek
()

Implements java.util.Queue.peek.

Always returns null.

public E

Returns:

the head of this queue, or null if the specified waiting time elapses before an element is present
poll
(long
how long to wait before giving up, in units of unit
timeout
,
TimeUnit
a TimeUnit determining how to interpret the timeout parameter
unit
)

Implements java.util.concurrent.BlockingQueue.poll.

Retrieves and removes the head of this queue, waiting if necessary up to the specified wait time, for another thread to insert it.

public E

Returns:

the head of this queue, or null if no element is available
poll
()

Implements java.util.Queue.poll.

Retrieves and removes the head of this queue, if another thread is currently making an element available.

public void
put(E
the element to add
e
)

Implements java.util.concurrent.BlockingQueue.put.

Adds the specified element to this queue, waiting if necessary for another thread to receive it.

private Object
readResolve()

Replaces a deserialized SynchronousQueue with a fresh one with the associated fairness

public int

Returns:

zero
remainingCapacity
()

Implements java.util.concurrent.BlockingQueue.remainingCapacity.

Always returns zero.

public boolean

Returns:

false
remove
(Object
the element to remove
o
)

Overrides java.util.AbstractCollection.remove.

Implements java.util.concurrent.BlockingQueue.remove, java.util.Collection.remove.

Always returns false.

public boolean

Returns:

false
removeAll
(Collection<?>
the collection
c
)

Overrides java.util.AbstractCollection.removeAll.

Implements java.util.Collection.removeAll.

Always returns false.

public boolean

Returns:

false
retainAll
(Collection<?>
the collection
c
)

Overrides java.util.AbstractCollection.retainAll.

Implements java.util.Collection.retainAll.

Always returns false.

public int

Returns:

zero
size
()

Implements abstract java.util.AbstractCollection.size.

Implements java.util.Collection.size.

Always returns zero.

public Spliterator<E>

Returns:

an empty spliterator
spliterator
()

Overrides default java.util.Collection.spliterator.

Returns an empty spliterator in which calls to trySplit always return null.

public E

Returns:

the head of this queue
take
()

Implements java.util.concurrent.BlockingQueue.take.

Retrieves and removes the head of this queue, waiting if necessary for another thread to insert it.

public Object[]

Returns:

a zero-length array
toArray
()

Overrides java.util.AbstractCollection.toArray.

Implements java.util.Collection.toArray.

Returns a zero-length array.

public <T> T[]

Returns:

the specified array
toArray
(T[]
the array
a
)

Overrides java.util.AbstractCollection.toArray.

Implements java.util.Collection.toArray.

Sets the zeroth element of the specified array to null (if the array has non-zero length) and returns it.

public String

Returns:

"[]"
toString
()

Overrides java.util.AbstractCollection.toString.

Always returns "[]".

private void
writeObject(ObjectOutputStream
the stream
s
)

Saves this queue to a stream (that is, serializes it).

private Object
xfer(Object e, long nanos)

Invokes fair or lifo transfer

Inherited from java.util.AbstractQueue:
addaddAllelementremove

Field Detail

fairback to summary
private final transient boolean fair
qlockback to summary
private ReentrantLock qlock
serialVersionUIDback to summary
private static final long serialVersionUID
transfererback to summary
private final transient SynchronousQueue.Transferer<E> transferer

The transferer. (See below about serialization.)

waitingConsumersback to summary
private SynchronousQueue.WaitQueue waitingConsumers
waitingProducersback to summary
private SynchronousQueue.WaitQueue waitingProducers

Constructor Detail

SynchronousQueueback to summary
public SynchronousQueue()

Creates a SynchronousQueue with nonfair access policy.

SynchronousQueueback to summary
public SynchronousQueue(boolean fair)

Creates a SynchronousQueue with the specified fairness policy.

Parameters
fair:boolean

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

Method Detail

clearback to summary
public void clear()

Overrides java.util.AbstractQueue.clear.

Implements java.util.Collection.clear.

Does nothing. A SynchronousQueue has no internal capacity.

containsback to summary
public boolean contains(Object o)

Overrides java.util.AbstractCollection.contains.

Implements java.util.concurrent.BlockingQueue.contains, java.util.Collection.contains.

Always returns false. A SynchronousQueue has no internal capacity.

Parameters
o:Object

the element

Returns:boolean

false

containsAllback to summary
public boolean containsAll(Collection<?> c)

Overrides java.util.AbstractCollection.containsAll.

Implements java.util.Collection.containsAll.

Returns false unless the given collection is empty. A SynchronousQueue has no internal capacity.

Parameters
c:Collection<?>

the collection

Returns:boolean

false unless given collection is empty

drainToback to summary
public int drainTo(Collection<? super E> c)

Implements java.util.concurrent.BlockingQueue.drainTo.

Doc from java.util.concurrent.BlockingQueue.drainTo.

Removes all available elements from this queue and adds them to the given collection. This operation may be more efficient than repeatedly polling this queue. A failure encountered while attempting to add elements to collection c may result in elements being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue to itself result in IllegalArgumentException. Further, the behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

Parameters
c:Collection<? super E>

the collection to transfer elements into

Returns:int

the number of elements transferred

Exceptions
UnsupportedOperationException:
if addition of elements is not supported by the specified collection
ClassCastException:
if the class of an element of this queue prevents it from being added to the specified collection
NullPointerException:
if the specified collection is null
IllegalArgumentException:
if the specified collection is this queue, or some property of an element of this queue prevents it from being added to the specified collection
drainToback to summary
public int drainTo(Collection<? super E> c, int maxElements)

Implements java.util.concurrent.BlockingQueue.drainTo.

Doc from java.util.concurrent.BlockingQueue.drainTo.

Removes at most the given number of available elements from this queue and adds them to the given collection. A failure encountered while attempting to add elements to collection c may result in elements being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue to itself result in IllegalArgumentException. Further, the behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

Parameters
c:Collection<? super E>

the collection to transfer elements into

maxElements:int

the maximum number of elements to transfer

Returns:int

the number of elements transferred

Exceptions
UnsupportedOperationException:
if addition of elements is not supported by the specified collection
ClassCastException:
if the class of an element of this queue prevents it from being added to the specified collection
NullPointerException:
if the specified collection is null
IllegalArgumentException:
if the specified collection is this queue, or some property of an element of this queue prevents it from being added to the specified collection
isEmptyback to summary
public boolean isEmpty()

Overrides java.util.AbstractCollection.isEmpty.

Implements java.util.Collection.isEmpty.

Always returns true. A SynchronousQueue has no internal capacity.

Returns:boolean

true

iteratorback to summary
public Iterator<E> iterator()

Implements abstract java.util.AbstractCollection.iterator.

Implements java.util.Collection.iterator.

Returns an empty iterator in which hasNext always returns false.

Returns:Iterator<E>

an empty iterator

offerback to summary
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException

Implements java.util.concurrent.BlockingQueue.offer.

Inserts the specified element into this queue, waiting if necessary up to the specified wait time for another thread to receive it.

Parameters
e:E

Doc from java.util.concurrent.BlockingQueue.offer.

the element to add

timeout:long

Doc from java.util.concurrent.BlockingQueue.offer.

how long to wait before giving up, in units of unit

unit:TimeUnit

Doc from java.util.concurrent.BlockingQueue.offer.

a TimeUnit determining how to interpret the timeout parameter

Returns:boolean

true if successful, or false if the specified waiting time elapses before a consumer appears

Exceptions
InterruptedException:
if interrupted while waiting
NullPointerException:
if the specified element is null
offerback to summary
public boolean offer(E e)

Implements java.util.concurrent.BlockingQueue.offer, java.util.Queue.offer.

Inserts the specified element into this queue, if another thread is waiting to receive it.

Parameters
e:E

the element to add

Returns:boolean

true if the element was added to this queue, else false

Exceptions
NullPointerException:
if the specified element is null
peekback to summary
public E peek()

Implements java.util.Queue.peek.

Always returns null. A SynchronousQueue does not return elements unless actively waited on.

Returns:E

null

pollback to summary
public E poll(long timeout, TimeUnit unit) throws InterruptedException

Implements java.util.concurrent.BlockingQueue.poll.

Retrieves and removes the head of this queue, waiting if necessary up to the specified wait time, for another thread to insert it.

Parameters
timeout:long

Doc from java.util.concurrent.BlockingQueue.poll.

how long to wait before giving up, in units of unit

unit:TimeUnit

Doc from java.util.concurrent.BlockingQueue.poll.

a TimeUnit determining how to interpret the timeout parameter

Returns:E

the head of this queue, or null if the specified waiting time elapses before an element is present

Annotations
@SuppressWarnings:unchecked
Exceptions
InterruptedException:
if interrupted while waiting
pollback to summary
public E poll()

Implements java.util.Queue.poll.

Retrieves and removes the head of this queue, if another thread is currently making an element available.

Returns:E

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

Annotations
@SuppressWarnings:unchecked
putback to summary
public void put(E e) throws InterruptedException

Implements java.util.concurrent.BlockingQueue.put.

Adds the specified element to this queue, waiting if necessary for another thread to receive it.

Parameters
e:E

Doc from java.util.concurrent.BlockingQueue.put.

the element to add

Exceptions
InterruptedException:
if interrupted while waiting
NullPointerException:
if the specified element is null
readResolveback to summary
private Object readResolve()

Replaces a deserialized SynchronousQueue with a fresh one with the associated fairness

remainingCapacityback to summary
public int remainingCapacity()

Implements java.util.concurrent.BlockingQueue.remainingCapacity.

Always returns zero. A SynchronousQueue has no internal capacity.

Returns:int

zero

removeback to summary
public boolean remove(Object o)

Overrides java.util.AbstractCollection.remove.

Implements java.util.concurrent.BlockingQueue.remove, java.util.Collection.remove.

Always returns false. A SynchronousQueue has no internal capacity.

Parameters
o:Object

the element to remove

Returns:boolean

false

removeAllback to summary
public boolean removeAll(Collection<?> c)

Overrides java.util.AbstractCollection.removeAll.

Implements java.util.Collection.removeAll.

Always returns false. A SynchronousQueue has no internal capacity.

Parameters
c:Collection<?>

the collection

Returns:boolean

false

retainAllback to summary
public boolean retainAll(Collection<?> c)

Overrides java.util.AbstractCollection.retainAll.

Implements java.util.Collection.retainAll.

Always returns false. A SynchronousQueue has no internal capacity.

Parameters
c:Collection<?>

the collection

Returns:boolean

false

sizeback to summary
public int size()

Implements abstract java.util.AbstractCollection.size.

Implements java.util.Collection.size.

Always returns zero. A SynchronousQueue has no internal capacity.

Returns:int

zero

spliteratorback to summary
public Spliterator<E> spliterator()

Overrides default java.util.Collection.spliterator.

Returns an empty spliterator in which calls to trySplit always return null.

Returns:Spliterator<E>

an empty spliterator

Since
1.8
takeback to summary
public E take() throws InterruptedException

Implements java.util.concurrent.BlockingQueue.take.

Retrieves and removes the head of this queue, waiting if necessary for another thread to insert it.

Returns:E

the head of this queue

Annotations
@SuppressWarnings:unchecked
Exceptions
InterruptedException:
if interrupted while waiting
toArrayback to summary
public Object[] toArray()

Overrides java.util.AbstractCollection.toArray.

Implements java.util.Collection.toArray.

Returns a zero-length array.

Returns:Object[]

a zero-length array

toArrayback to summary
public <T> T[] toArray(T[] a)

Overrides java.util.AbstractCollection.toArray.

Implements java.util.Collection.toArray.

Sets the zeroth element of the specified array to null (if the array has non-zero length) and returns it.

Parameters
<T>

Doc from java.util.Collection.toArray. the component type of the array to contain the collection

a:T[]

the array

Returns:T[]

the specified array

Exceptions
NullPointerException:
if the specified array is null
toStringback to summary
public String toString()

Overrides java.util.AbstractCollection.toString.

Always returns "[]".

Returns:String

"[]"

writeObjectback to summary
private void writeObject(ObjectOutputStream s) throws IOException

Saves this queue to a stream (that is, serializes it).

Parameters
s:ObjectOutputStream

the stream

Exceptions
IOException:
if an I/O error occurs
xferback to summary
private Object xfer(Object e, long nanos)

Invokes fair or lifo transfer

java.util.concurrent back to summary

pack-priv Class SynchronousQueue.FifoWaitQueue

extends WaitQueue
Class Inheritance

Field Summary

Modifier and TypeField and Description
private static final long

Constructor Summary

AccessConstructor and Description
pack-priv

Field Detail

serialVersionUIDback to summary
private static final long serialVersionUID

Constructor Detail

FifoWaitQueueback to summary
pack-priv FifoWaitQueue()
java.util.concurrent back to summary

pack-priv Class SynchronousQueue.LifoWaitQueue

extends WaitQueue
Class Inheritance

Field Summary

Modifier and TypeField and Description
private static final long

Constructor Summary

AccessConstructor and Description
pack-priv

Field Detail

serialVersionUIDback to summary
private static final long serialVersionUID

Constructor Detail

LifoWaitQueueback to summary
pack-priv LifoWaitQueue()
java.util.concurrent back to summary

pack-priv final Class SynchronousQueue.Transferer<E>

extends LinkedTransferQueue<E>
Class Inheritance
Annotations
@SuppressWarnings:serial

Extension of LinkedTransferQueue to support Lifo (stack) mode. Methods use the "head" field as head (top) of stack (versus queue). Note that popped nodes are not self-linked because they are not prone to unbounded garbage chains. Also note that "async" mode is never used and not supported for synchronous transfers.

Field Summary

Inherited from java.util.concurrent.LinkedTransferQueue:
headHEADSWEEP_THRESHOLDsweepVotesSWEEPVOTEStailTAIL

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
private void
pack-priv final Object

Returns:

an item if matched, else e
xferLifo
(Object
the item or null for take
e
,
long
timeout or 0 if immediate, Long.MAX_VALUE if untimed
ns
)

Puts or takes an item with lifo ordering.

Inherited from java.util.concurrent.LinkedTransferQueue:
addclearcmpExHeadcmpExTailcontainscountOfModedrainTodrainTofirstDataNodeforEachforEachFromgetWaitingConsumerCounthasWaitingConsumerisEmptyiteratorofferofferpeekpollpollputremainingCapacityremoveremoveAllremoveIfretainAllsizeskipDeadNodesspliteratorsweepNowtaketoArraytoArraytoStringtransfertryCasSuccessortryMatchDatatryTransfertryTransferxfer

Constructor Detail

Transfererback to summary
pack-priv Transferer()

Method Detail

unspliceLifoback to summary
private void unspliceLifo(LinkedTransferQueue.DualNode s)

Unlinks node s. Same idea as Fifo version.

xferLifoback to summary
pack-priv final Object xferLifo(Object e, long ns)

Puts or takes an item with lifo ordering. Loops trying: * If top (var p) exists and is already matched, pop and continue * If top has complementary type, try to fulfill by CASing item, On success pop (which will succeed unless already helped), otherwise restart. * If no possible match, unless immediate mode, push a node and wait, later unsplicing if cancelled.

Parameters
e:Object

the item or null for take

ns:long

timeout or 0 if immediate, Long.MAX_VALUE if untimed

Returns:Object

an item if matched, else e

java.util.concurrent back to summary

pack-priv Class SynchronousQueue.WaitQueue

extends Object
implements Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable
Known Direct Subclasses
java.util.concurrent.SynchronousQueue.LifoWaitQueue, java.util.concurrent.SynchronousQueue.FifoWaitQueue
Annotations
@SuppressWarnings:serial

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

WaitQueueback to summary
pack-priv WaitQueue()