Java Concurrency - (Queue|Stack)

1 - About

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

3 - Interface and Implementation

Java Concurrency - java.util.concurrent Interface and Implementation

3.1 - 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.

3.2 - Non-blocking queue

3.3 - 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

4 - End of Queue

4.1 - 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");

5 - Documentation / Reference

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap