Java.Multithreading.What is Semaphore?

🔐 What is a Semaphore?

A Semaphore maintains a set of permits — threads must acquire a permit before proceeding, and release it when done.

💡 If no permits are available, the thread blocks (waits) until one is released.


✅ Real-Life Analogy:

Imagine:

  • A parking lot with 3 spots.
  • Only 3 cars can park at once.
  • A car has to wait if all spots are full.

🎯 The 3 parking spots = 3 permits in a Semaphore

🔧 Java API: java.util.concurrent.Semaphore

Semaphore semaphore = new Semaphore(3); // 3 permits

✅ Example

Semaphore semaphore = new Semaphore(2); // Only 2 threads can run at once

Runnable task = () -> {
    try {
        semaphore.acquire(); // Get a permit
        System.out.println(Thread.currentThread().getName() + " acquired permit");
        Thread.sleep(1000); // Simulate work
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        System.out.println(Thread.currentThread().getName() + " released permit");
        semaphore.release(); // Release permit
    }
};

for (int i = 0; i < 5; i++) {
    new Thread(task).start();
}

🧠 What Happens:

  • Only 2 threads run at the same time.
  • Others wait until a permit is released.

📘 Key Methods

MethodDescription
acquire()Acquires a permit (waits if none are available)
release()Releases a permit
tryAcquire()Attempts to acquire a permit without waiting
availablePermits()Shows how many permits are available right now

🚦 Binary Semaphore = Mutex

Semaphore mutex = new Semaphore(1); // Only one thread at a time

This behaves like a lock — only one thread can enter the critical section at a time.


🔄 Semaphore vs Lock

FeatureSemaphoreLock / synchronized
Multiple access?✅ Yes (N threads)❌ No (1 thread at a time)
Resource control✅ Ideal for managing limited resources❌ Basic mutual exclusion
Fairness option✅ Yes (new Semaphore(permits, true))✅ with ReentrantLock

🎯 Use Cases

  • Limiting concurrent database connections
  • Controlling access to a pool of resources
  • Implementing rate limiting
  • Simulating barriers or entry gates
This entry was posted in Без рубрики. Bookmark the permalink.