Stacks and BlockingQueue


Stacks

What is a Stack?

In Java, Stacks are a LIFO (Last In, First Out) Data structure for objects.

Stack API

Java contains a Stack API with the following methods

Stack() //Creates an empty Stack
isEmpty() //Is the Stack Empty? Return Type: Boolean
push(Item item) //push an item onto the stack
pop() //removes item from top of stack Return Type: Item
size() //returns # of items in stack Return Type: Int

Example

import java.util.*;
 
public class CustomStackExample {
    public static void main(String args[]) {
        Stack customStack = new Stack();
        System.out.println("Custom stack: " + customStack);
 
        customStack.push(5);
        System.out.println("5 was pushed to the custom stack");
        System.out.println("Custom stack: " + customStack);
 
        customStack.push(8);
        System.out.println("8 was pushed to the custom stack");
        System.out.println("Custom stack: " + customStack);
 
        customStack.push(20);
        System.out.println("20 was pushed to the custom stack");
        System.out.println("Custom stack: " + customStack);
 
        customStack.pop();
        System.out.println("20 was popped from the custom stack");
        System.out.println("Custom stack: " + customStack);
 
        customStack.pop();
        System.out.println("8 was popped from the custom stack");
        System.out.println("Custom stack: " + customStack);
 
        customStack.pop();
        System.out.println("5 was popped from the custom stack");
        System.out.println("Custom stack: " + customStack);
 
        if (customStack.isEmpty()) {
            System.out.println("Empty custom stack");
        }
    }
}

Output

Custom stack: []
5 was pushed to the custom stack
Custom stack: [5]
8 was pushed to the custom stack
Custom stack: [5, 8]
20 was pushed to the custom stack
Custom stack: [5, 8, 20]
20 was popped from the custom stack
Custom stack: [5, 8]
8 was popped from the custom stack
Custom stack: [5]
5 was popped from the custom stack
Custom stack: []
Empty custom stack

BlockingQueue

A BlockingQueue is an interface, which is a queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full. A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. A thread trying to enqueue an item in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more items or clearing the queue completely.

BlockingQueue methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up.

Operation Throws Exception Special Value Blocks Times out
Insert add() offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() N/A N/A

A BlockingQueue can be bounded or unbounded. A bounded BlockingQueue is one which is initialized with initial capacity.

BlockingQueue<String> bQueue = new ArrayBlockingQueue<String>(2);

Any calls to a put() method will be blocked if the size of the queue is equal to the initial capacity defined.

An unbounded Queue is one which is initialized without capacity, actually by default it initialized with Integer.MAX_VALUE.

Some common implementations of BlockingQueue are:

  • ArrayBlockingQueue
  • LinkedBlockingQueue
  • PriorityBlockingQueue

Now let's look at an example of ArrayBlockingQueue:

import java.util.concurrent.*;
 
public class BlockingQueueExample {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
 
        queue.put("First item");
        System.out.println("First item added");
 
        queue.put("Second item");
        System.out.println("Second item added");
 
        queue.put("Third item");
        System.out.println("Third item added");
    }
}

Output

First item added
Second item added

And the thread will be blocked after the second output.

Basic Programs