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, withacquire()
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