Concurrency in Java: What is "Semaphore" and its use?

  • 4.0/5
  • 4809
  • Jul 20, 2024

A Semaphore is a thread synchronization construct that can be used to limit the number of concurrent threads accessing a specific resource.

In general, a semaphore maintains a set of permits, each acquire() will take a permit from semaphore, each release() will return back the permit to the semaphore.

If permits are not available, acquire() will block until one is available.

Java 5 comes with a built-in Semaphore implementations in the java.util.concurrent package, so you don't have to implement your own.

There are two constructors in the java.util.concurrent.Semaphore class.

Semaphore(int num)

The "num" parameter specifies the initial permit count or the number of threads that can access a shared resource at a time.

Semaphore(int num, boolean how)

By default, all blocked threads are granted a permit in an undefined order. By setting "how" to "true", you can ensure that waiting threads are granted a permit in the order in which they requested access.

Semaphore example

Using Semaphores as Locks

A semaphore initialized to one, and which is used such that it only has at most one permit available, can be used as a lock.

Count: 0

Using Semaphores for Signaling

Semaphore can also be used to send signals between threads - call acquire() in place of wait() and release() in place of notify().

If the call to release() happens before the call to acquire(), the thread calling acquire() will still get the available permit, released by the other thread calling release().

Index
Modern Java - What’s new in Java 9 to Java 17

32 min

What is differences between JDK, JVM and JRE ?

2 min

What is ClassLoader in Java ?

2 min

Object Oriented Programming (OOPs) Concept

17 min

Concurrency in Java: Creating and Starting a Thread

12 min

Concurrency in Java: Interrupting and Joining Threads

5 min

Concurrency in Java: Race condition, critical section, and atomic operations

13 min

Concurrency in Java: Reentrant, Read/Write and Stamped Locks

11 min

Concurrency in Java: "synchronized" and "volatile" keywords

10 min

Concurrency in Java: using wait(), notify() and notifyAll()

6 min

Concurrency in Java: What is "Semaphore" and its use?

2 min

Concurrency in Java: CompletableFuture and its use

18 min

Concurrency in Java: Producer-consumer problem using BlockingQueue

2 min

Concurrency in Java: Producer-Consumer Problem

2 min

Concurrency in Java: Thread pools, ExecutorService & Future

14 min

Java 8 Lambdas, Functional Interface & "static" and "default" methods

28 min

Method Reference in Java (Instance, Static, and Constructor Reference)

9 min

What’s new in Java 21: A Tour of its Most Exciting Features

14 min

Java Memory Leaks & Heap Dumps (Capturing & Analysis)

9 min

Memory footprint of the JVM (Heap & Non-Heap Memory)

15 min