Advanced Java October 06 ,2025

Semaphore in Java

Complete Guide with Custom Implementation

Introduction

In multithreading, a Semaphore is used to control access to a shared resource by multiple threads.
It acts as a counter representing the number of permits available.

A Semaphore is part of the java.util.concurrent package.
It can be used for controlling concurrency in cases where a resource has a limited number of slots.

Key Points:

  • Semaphores maintain a set of permits.
  • Threads acquire permits before accessing a resource and release them afterward.
  • Semaphores can be binary (only 1 permit) or counting (multiple permits).
  • Used for controlling access to limited resources such as database connections.

How Semaphore Works

  • A thread calls acquire() to get a permit.
  • If permits are available, the thread continues; otherwise, it waits.
  • After finishing work, the thread calls release() to return the permit.

Syntax:

Semaphore semaphore = new Semaphore(int permits);

Here:

  • permits = maximum number of permits available.

Example: Using Semaphore

Let’s create a scenario where three threads access a shared resource with only two permits.

Code:

import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2); // 2 permits

        Runnable task = () -> {
            try {
                System.out.println(Thread.currentThread().getName() + " is waiting for a permit.");
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + " acquired a permit.");
                Thread.sleep(2000); // simulate resource usage
                System.out.println(Thread.currentThread().getName() + " releasing permit.");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

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

Expected Output:

Thread-0 is waiting for a permit.
Thread-0 acquired a permit.
Thread-1 is waiting for a permit.
Thread-1 acquired a permit.
Thread-2 is waiting for a permit.
Thread-3 is waiting for a permit.
Thread-4 is waiting for a permit.
Thread-0 releasing permit.
Thread-2 acquired a permit.
Thread-1 releasing permit.
Thread-3 acquired a permit.
...

Key Methods in Semaphore

MethodDescription
acquire()Acquires a permit (blocks if none available)
release()Releases a permit
availablePermits()Returns the number of available permits
tryAcquire()Attempts to acquire a permit without blocking

Advantages of CustomSemaphore

  • Helps understand concurrency control and permits logic.
  • Useful for learning how to manage resource access manually.
  • Simple, flexible for custom needs.

 Disadvantages

  • More prone to errors compared to Java’s built-in Semaphore.
  • No advanced features like fairness and interruption handling.
  • Needs careful design to avoid deadlocks.

 Real-World Use Case

CustomSemaphore can be useful for:

  • Limiting access to resources like database connections or API calls.
  • Controlling concurrency in thread pools.
  • Traffic shaping in networked applications.

The custom implementation of semaphore use the below link:

Custom implementation of Semaphore

Conclusion

Semaphore is a powerful tool for controlling access to resources.
The custom implementation of Semaphore provides insight into low-level concurrency control, teaching how permits and synchronization work.

For production-grade applications, always use Java’s built-in Semaphore because it handles edge cases, fairness, and interruption effectively.
But building a custom version deepens understanding of concurrency principles.

 

 

 

Sanjiv
0

You must logged in to post comments.

Related Blogs

Generics P...
Advanced Java August 08 ,2025

Generics Part- 2

Collection...
Advanced Java July 07 ,2025

Collections Framewor...

Mastering...
Advanced Java August 08 ,2025

Mastering Java Multi...

Annotation...
Advanced Java August 08 ,2025

Annotations

Java Memor...
Advanced Java August 08 ,2025

Java Memory Manageme...

Java Lambd...
Advanced Java August 08 ,2025

Java Lambda Expressi...

Java Funct...
Advanced Java August 08 ,2025

Java Functional Inte...

Java Strea...
Advanced Java August 08 ,2025

Java Stream API

JDBC (Java...
Advanced Java August 08 ,2025

JDBC (Java Database...

JDBC (Java...
Advanced Java September 09 ,2025

JDBC (Java Database...

Annotation...
Advanced Java August 08 ,2025

Annotations

Generics
Advanced Java August 08 ,2025

Generics

Java I/O (...
Advanced Java August 08 ,2025

Java I/O (NIO)

Introducti...
Advanced Java September 09 ,2025

Introduction to Desi...

Design Pat...
Advanced Java September 09 ,2025

Design Patterns in J...

Other Prin...
Advanced Java September 09 ,2025

Other Principles Beh...

Creational...
Advanced Java September 09 ,2025

Creational Design Pa...

In Creatio...
Advanced Java September 09 ,2025

In Creational Design...

In Creatio...
Advanced Java September 09 ,2025

In Creational Design...

Creational...
Advanced Java September 09 ,2025

Creational Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

In Creatio...
Advanced Java September 09 ,2025

In Creational Design...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Builder De...
Advanced Java September 09 ,2025

Builder Design Patte...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Design Pat...
Advanced Java September 09 ,2025

Design Patterns in J...

Chain of R...
Advanced Java September 09 ,2025

Chain of Responsibil...

Command De...
Advanced Java September 09 ,2025

Command Design Patte...

Interprete...
Advanced Java September 09 ,2025

Interpreter Design P...

Iterator D...
Advanced Java September 09 ,2025

Iterator Design Patt...

Mediator D...
Advanced Java September 09 ,2025

Mediator Design Patt...

Memento De...
Advanced Java September 09 ,2025

Memento Design Patte...

Observer D...
Advanced Java September 09 ,2025

Observer Design Patt...

State Desi...
Advanced Java September 09 ,2025

State Design Pattern...

Strategy D...
Advanced Java September 09 ,2025

Strategy Design Patt...

Template M...
Advanced Java September 09 ,2025

Template Method Desi...

Visitor De...
Advanced Java September 09 ,2025

Visitor Design Patte...

Prototype...
Advanced Java September 09 ,2025

Prototype Design Pat...

Java 8+ Fe...
Advanced Java October 10 ,2025

Java 8+ Features

SOLID Prin...
Advanced Java October 10 ,2025

SOLID Principles in...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

How Iterat...
Advanced Java October 10 ,2025

How Iterators Work i...

How Concur...
Advanced Java October 10 ,2025

How ConcurrentHashMa...

Comparable...
Advanced Java October 10 ,2025

Comparable vs Compar...

Get In Touch

G06, Kristal Olivine Bellandur near Bangalore Central Mall, Bangalore Karnataka, 560103

+91-8076082435

techiefreak87@gmail.com