Semaphores example limiting URL connections (original) (raw)

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:

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

Photo of Ilias Tsagklis

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

Back to top button