java.util.concurrent.Semaphore – Semaphore Java Example (original) (raw)

In this example, we will show you how to make use of the Semaphore – java.util.concurrent.Semaphore Class in Java.

1. What is a SEMAPHORE?

A semaphore in Computer Science is analogous to a Guard at the entrance of a building. However, this guard takes into account the number of people already entered the building. At any given time, there can be only a fixed amount of people inside the building. When a person leaves the building, the guard allows a new person to enter the building. In the computer science realm, this sort of guard is called a Semaphore. The concept of Semaphore was invented by Edsger Dijkstra in 1965.

Semaphore Java

The semaphores in computer science can be broadly classified as :

Binary Semaphore has only two states on and off(lock/unlock).(can be implemented in Java by initializing Semaphore to size 1.)
The java.util.concurrent.Semaphore Class implements a counting Semaphore.

2. Features of Semaphore Class in Java

SemaphoreDemo.java

01020304050607080910111213141516171819202122232425262728293031323334353637383940414243 package com.javacodegeeks.examples.concurrent;import java.util.concurrent.Semaphore;/** * @author Chandan Singh *This class demonstrates the use of java.util.concurrent.Semaphore Class */public class SemaphoreDemo{ Semaphore semaphore = new Semaphore(10); public void printLock() { try { semaphore.acquire(); System.out.println("Locks acquired"); System.out.println("Locks remaining >> " +semaphore.availablePermits()); } catch(InterruptedException ie) { ie.printStackTrace(); } finally { semaphore.release(); System.out.println("Locks Released"); } } public static void main(String[] args) { final SemaphoreDemo semaphoreDemo = new SemaphoreDemo(); Thread thread = new Thread(){ @Override public void run() { semaphoreDemo.printLock(); }}; thread.start(); }}

Output:

123 Locks acquiredLocks remaining >> 9Locks Released

3. Applications

One of the major application of Semaphore is while the creation of pooled resources like Database connections.

4. Download the Source Code

We have studied what semaphores are in Java, and how we can use them in our programs.

Last updated on June 01st, 2020

Photo of Chandan Singh

Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.

Back to top button