concurrent

Semaphores example limiting URL connections

In this example we shall show you how to use a Semaphore for limiting URL connections. We have implemented a class, ConnectionLimiter that uses a Semaphore and is described below:

  • It creates a new Semaphore with a given number of permits.
  • It implements a method, URLConnection acquire(URL url). The method acquires a permit from this semaphore, blocking until one is available, with acquire() API method of Semaphore. Then it returns a URLConnection instance that represents a connection to the remote object referred to by the given url.
  • The class also implements the release(URLConnection conn) method, that after doing any clean up operation for the url, releases the acquired permit, returning it to the semaphore,

as described in the code snippet below.

public class ConnectionLimiter {
   private final Semaphore semaphore;
 
   private ConnectionLimiter(int maxConcurrentRequests) {

 semaphore = new Semaphore(maxConcurrentRequests);
   }
 
   public URLConnection acquire(URL url) throws InterruptedException,








IOException {

 semaphore.acquire();

 return url.openConnection();
   }
 
   public void release(URLConnection conn) {

 try {

     /*

     * ... clean up here

     */

 } finally {

     semaphore.release();

 }
   }
}

 
This was an example of how to use a Semaphore for limiting URL connections in Java.
 

Related Article:

Reference: Java Concurrency Part 1 – Semaphores from our JCG partners at the Carfey Software blog

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button