Thread-Safe Stack and Queue

Easy
ConcurrencyMutexSemaphoreThread SafetyData StructuresCAS

Problem Statement

Implement two thread-safe data structures from scratch — a stack (LIFO) and a queue (FIFO) — without using Java's built-in concurrent collections. Both must support concurrent push/pop (or enqueue/dequeue) from multiple threads.

class ThreadSafeStack<T> {
    public void push(T item) {}
    public T pop() throws EmptyStackException {}
    public T peek() throws EmptyStackException {}
    public boolean isEmpty() {}
    public int size() {}
}

class ThreadSafeQueue<T> {
    public void enqueue(T item) {}
    public T dequeue() throws NoSuchElementException {} // Non-blocking: throws if empty
    public T dequeueBlocking() throws InterruptedException {} // Blocks until element available
    public boolean isEmpty() {}
    public int size() {}
}

Key Entities

  • LinkedList or array: Internal storage.
  • ReentrantLock / synchronized: Mutual exclusion on structural modifications.
  • Condition variable: For dequeueBlocking() to await non-empty.
  • AtomicReference (bonus): Lock-free implementation using CAS (Treiber stack).

Requirements

  1. All operations are thread-safe.
  2. pop() and dequeue() throw on empty without blocking.
  3. dequeueBlocking() waits until an element is available.
  4. No data races or lost updates under concurrent access.
  5. Bonus: Implement the lock-free Treiber Stack using AtomicReference.

Asked at: Amazon, Google, Microsoft, Adobe, Flipkart

!Constraints

- Stack and queue are unbounded (no capacity limit) unless specified. - Items are non-null objects. - Concurrent push+pop from 100 threads must not corrupt internal state. - isEmpty() and size() must return accurate values under concurrency.
Output

Run or submit your code to see output here.