Java.Multithreading.Write a minimal non-blocking stack (only two methods – push() and pop()) using Semaphore.

✅ Minimal Blocking Stack Using Semaphore

This stack:

  • Uses a Deque to store elements
  • Uses a Semaphore to track available elements
  • Is thread-safe, but not lock-free (uses internal synchronization)
import java.util.Deque;
import java.util.LinkedList;
import java.util.concurrent.Semaphore;

public class SemaphoreStack<T> {
    private final Deque<T> stack = new LinkedList<>();
    private final Semaphore items = new Semaphore(0); // Tracks how many items are available
    private final Object lock = new Object(); // Guards access to the stack

    public void push(T value) {
        synchronized (lock) {
            stack.push(value);
        }
        items.release(); // Signal: one more item available
    }

    public T pop() throws InterruptedException {
        items.acquire(); // Wait until item is available
        synchronized (lock) {
            return stack.pop();
        }
    }
}

🧪 Example Usage:

public class Main {
    public static void main(String[] args) throws InterruptedException {
        SemaphoreStack<Integer> stack = new SemaphoreStack<>();

        stack.push(1);
        stack.push(2);

        System.out.println(stack.pop()); // 2
        System.out.println(stack.pop()); // 1
    }
}

🔍 How It Works:

  • items.acquire() blocks if the stack is empty
  • items.release() increases the count (available items)
  • synchronized protects the internal stack from race conditions

🧠 Summary

FeatureSemaphore Stack
Thread-safe?✅ Yes
Lock-free?❌ No (uses synchronized)
Blocking behavior?✅ Yes (pop blocks if empty)
Use case?Thread coordination, bounded stacks, consumer-producer models
This entry was posted in Без рубрики. Bookmark the permalink.