Semaphore Example in Java ?

By | June 23, 2020

In this post, We will talk and learn about Semaphore in Java using an Example.

A counting Semaphore is from java.util.concurrent package which maintains a set of permits.

Each call of acquire() blocks if necessary until a permit is available, and then takes it. Each call of release() adds a permit.

The Semaphore usually keeps a count of the number available and acts accordingly.

Semaphores are usually used to restrict the number of threads than can access some (physical or logical) resources. For example, A semaphore to control access to a pool of items.

Connection.java

ClientTest.java

Output of this Program:

Current connection:1
Current connection:2
Current connection:3
Current connection:4
Current connection:5
Current connection:6
Current connection:7
Current connection:8
Current connection:9
Current connection:10
Current connection:1
Current connection:2
Current connection:3
Current connection:4
Current connection:5
Current connection:6
Current connection:7
Current connection:8
Current connection:9
Current connection:10

Above Output shows Semaphore always maintains 10 connections in Pool

You May Also Like:

How would you round a double value to certain decimal Precision and Scale ?
What is BlockingQueue? How can we implement Producer and Consumer problem using Blocking Queue?
How to get number of available processors in Java ?

That’s all about  Semaphore Example in Java?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published.