Why is a Java Semaphore useful? Today I’ll tell you the four reasons why a Java Semaphore is useful.
This is part two of a series on Java concurrency. Part one was about the synchronization of threads using CountDownLatch.
java.util.concurrent.Semaphore can be used to restrict access to finite resources. The number of concurrent clients accessing a finite resource can be capped with a Counting Semaphore. Throttling access to finite system resources, improves system stability and performance.
The four reasons why a Java Counting Semaphore is useful are listed below. A Java Counting Semaphore can be used to restrict the maximum amount of:
- Database connections – to stop disk trashing
- TCP/IP output connections – to prevent exhaustion of system resources
- Threads – too many threads reduces application performance
- Memory – any collections size can be restricted with the use of a Counting Semaphore
Pertinent methods are presented:
Semaphore(int permits): Permits, is the maximum number of concurrent clients, allowed to access the resource
acquire(): Acquires a permit (to access a protected resource). If a permit is not available this call blocks until a permit is available.
release(): Once the client has finished using the resource, the client calls this method to free the resource for others to use
In the following example
UrlPool class constrains the maximum number of connections allowed to access an external server. This stops putting a server under too much load. The example has been simplified to only allow one connection to the external server, however the maximum number of outbound connections could be set to a higher number.
Click on the flashing arrow to step through the example.
Http iframes are not shown in https pages in many major browsers. Please read this post for details.
image source: ITU images, image modified