Thread-Safe Stack Using Linked List

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-10-20

Problem Statement

Design and implement a thread-safe stack data structure backed by a linked list. The stack should support concurrent operations from multiple threads while preserving correctness (LIFO order) and preventing race conditions.


Functional Requirements


1.<span></span>Core APIs
2.<span></span>push(value) → Insert an element on top of the stack.
3.<span></span>pop() → Remove and return the top element. If the stack is empty, return an appropriate error/exception.
4.<span></span>peek() → Return the top element without removing it.
5.<span></span>isEmpty() → Return whether the stack is empty.
6.<span></span>Concurrency
7.<span></span>Multiple threads should be able to call push and pop simultaneously.
8.<span></span>No data corruption, missed elements, or incorrect ordering should occur.
9.<span></span>Must avoid deadlocks and race conditions.
10.<span></span>Data Structure
11.<span></span>Internally use a singly linked list where the head node represents the top of the stack.


Constraints


1.<span></span>Use low-level synchronization primitives (mutex/lock, condition_variable, or atomic operations).
2.<span></span>Do not use prebuilt concurrent collections (ConcurrentStack, etc.).
3.<span></span>Support up to 1000 concurrent threads.
4.<span></span>Must guarantee O(1) time complexity for push and pop.


Example Usage

<div><div>java</div><div>CopyEdit</div><div>ThreadSafeStack<Integer> stack = new ThreadSafeStack<>();</div><div><br /></div><div>// Thread-1</div><div>stack.push(10);</div><div><br /></div><div>// Thread-2</div><div>stack.push(20);</div><div><br /></div><div>// Thread-3</div><div>System.out.println(stack.pop()); // returns 20</div></div>


Deliverables


1.<span></span>Class design (e.g., Node, ThreadSafeStack).
2.<span></span>Correctly synchronized implementation of push and pop.
3.<span></span>Unit tests with multiple producer/consumer threads.
4.<span></span>Stress test showing no lost or duplicated elements under concurrency.


Solution

Comments