Java Concurrency - (Queue|Stack)

Java Conceptuel Diagram


Collection - Queue (FIFO) and Collection - Stack (LIFO) in Java concurrency context

Interface and Implementation

Java Concurrency - java.util.concurrent Interface and Implementation

Blocking queue

The BlockingQueue interface defines a first-in-first-out data structure that blocks or times out when you attempt to:

  • add to a full queue, (put method)
  • or retrieve from an empty queue. (take and remove methods)

BlockingQueue implementations are designed to be used primarily for producer-consumer queues.

The BlockingDeque interface extends BlockingQueue to support both FIFO and LIFO (stack-based) operation.

After some tests, ArrayBlockingQueue seems to be quicker than the LinkedBlockingQueue.

Non-blocking queue

Synchronous transfer (between producer and consumer)

Extended interface TransferQueue, and implementation LinkedTransferQueue introduce a synchronous transfer method (along with related features) in which a producer may optionally block awaiting its consumer.

See Data Concurrency - Producer Consumer Thread

End of Queue

End-of-stream or poison objects

From the Blocking Queue doc

A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation to indicate that no more items will be added. The needs and usage of such features tend to be implementation-dependent. 

A common tactic is for producers to insert special end-of-stream or poison objects, that are interpreted accordingly when taken by consumers.

A end-of-stream or poison objects is a marker object that is added to the queue in order to mark the end of the queue.

Code example in the consumer:

while (true) {
         String element = queue.take();
         if ("EndOfStream".equals(element)) {
                 System.out.println("End of Queue quiting");

Documentation / Reference

Discover More
Java Conceptuel Diagram
Java Concurrency - (Concurrent) Collections

All of the concurrent collections help avoid Memory Consistency Errors by defining a happens-before relationship between: an operation that adds an object to the collection with subsequent operations...
Data System Architecture
Parallel Programming - Producer Consumer problem (Bounded-buffer problem)

The producer–consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem in a producer consumer mode. The problem describes two processes...

Share this page:
Follow us:
Task Runner