Hackforge Academy

Category: java

What Is a Semaphore?

Published on 27 Oct 2026

Explanation

Semaphore maintains a number of permits that control concurrent access to a resource. A thread acquires a permit before entering and releases it when finished. A semaphore with one permit can act as a simple access limiter.

Code:

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(2);
        semaphore.acquire();
        try { System.out.println("Permit acquired"); }
        finally { semaphore.release(); }
    }
}

Explanation

A semaphore can cap the number of concurrent operations, such as calls to a constrained external service. Acquire a permit before the operation and release it in finally so failures do not leak permits.

Code:

import java.util.concurrent.Semaphore;

class ApiLimiter {
    private final Semaphore permits = new Semaphore(3);
    public void callApi() throws InterruptedException {
        permits.acquire();
        try { System.out.println("Calling external API"); }
        finally { permits.release(); }
    }
}

Explanation

acquire() waits until a permit is available and responds to interruption. tryAcquire() can return immediately if no permit is available, while a timed overload waits only for a specified duration.

Code:

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class TryAcquireDemo {
    public static void main(String[] args) throws InterruptedException {
        Semaphore sem = new Semaphore(1);
        if (sem.tryAcquire(200, TimeUnit.MILLISECONDS)) {
            try { System.out.println("Access granted"); }
            finally { sem.release(); }
        } else System.out.println("Try again later");
    }
}

Explanation

A fair Semaphore grants permits in FIFO order to threads queued for acquisition, subject to the API's fairness rules. A non-fair semaphore may allow a newly arriving thread to acquire a permit ahead of waiting threads, which can improve throughput.

Code:

import java.util.concurrent.Semaphore;

public class FairSemaphoreDemo {
    public static void main(String[] args) {
        Semaphore fair = new Semaphore(2, true);
        System.out.println("Available permits: " + fair.availablePermits());
    }
}

Explanation

synchronized allows one thread at a time to enter code protected by a monitor. A semaphore can allow a configured number of concurrent users and does not require the releasing thread to be the same thread that acquired the permit.

Code:

import java.util.concurrent.Semaphore;

public class ConnectionPool {
    private final Semaphore slots = new Semaphore(5);
    public void useConnection() throws InterruptedException {
        slots.acquire();
        try { System.out.println("Using a connection slot"); }
        finally { slots.release(); }
    }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community