SynchronousQueue VS TransferQueue
One addition in Java 7 is an interface TransferQueue in addition already exists from Java 5 SynchronousQueue. What is the reason of new interface?
- Firstly about TransferQueue
- Couple words about SynchronousQueue
- SynchronousQueue vs TransferQueue
Firstly about TransferQueue
Java 7 included new interface TransferQueue and corresponded implementation LinkedTransferQueue.
TransferQueue extends BlockingQueue which extends Queue interface, added in Java 5. BlockingQueue is a queue, which can block Producer threads during adding items into a full queue and Consumer threads, during removing from an empty queue. Main idea of blocking queues is to cope with flood of data, which can not be processed by system for appropriate time.
TransferQueue goes further, and blocks Producer threads until the items consumed by Consumer threads. New method —
transfer — blocking occurs until item moves from one thread to another.
There are additional methods — two forms of
tryTransfer — one is blocking with time-out, other is non-blocking but transfer only if Consumer thread is waiting. Also there are a couple helper methods
Couple words about SynchronousQueue
We remember about SynchronousQueue from Java 5, which provides queue with size 0 and quite good for transfer items between threads. This queue works on the principle «one came in — one went out». Each put operation blocks Producer thread until Consumer thread fetch element from queue and vice versa, Consumer thread is waiting until Producer thread puts element to queue.
SynchronousQueue is more specialized in comparison with TransferQueue but it allows developers decide whether to use general blocking queue, or guaranteed hand-off.
SynchronousQueue vs TransferQueue
LinkedTransferQueue combines advantages of ConcurrentLinkedQueue, SynchronousQueue (in «fair» mode) and unlimited LinkedBlockingQueues.
According to authors LinkedTransferQueue (William Scherer, Doug Lea, and Michael Scott Scalable Synchronous Queues) performance tests shows improvements over existing Java 5 alternatives. LinkedTransferQueue outperforms SynchronousQueue by a factor from 3 till 14 according to «fair» mode. Since SynchronousQueue is used in transfer tasks in ThreadPoolExecutor, in result you can expect performance improvements. Considering importance Executor in concurrent programming, it becomes clear the importance of adding new implementation.
SynchronousQueue uses dual queues — for waiting producers and consumers — and protect both queues with single lock. LinkedTransferQueue uses CAS operations to perform non-blocking algorithms and allows to avoid serialization bottlenecks.
That's all for now.
Localized versionsOther language versions:
- Русская версия — SynchronousQueue или TransferQueue
Don’t hesitate to comment below if you have any questions. Feel free to join the conversation.
This blog is about Java development and describes in detail the most interesting topics