Counting Semaphore

A counting semaphore is an integer value limited to some maximum value which can be increased or decreased. For example, for , this means the semaphore has reusable ‘permits’ available. When a permit is requested, it is granted and the number of available permits is reduced to . And so forth until zero, where no more can be granted.

Link to original

Semaphores in Java

class DbConnection {
	public static final int MAX_CONNECTIONS = 5;
	private Semphore semaphore = new Semaphore(MAX_CONNECTIONS);
	
	public boolean connect() {
		try {
			return semaphore.tryAcquire(100, TimeUnit.MILLISECONDS);
		} catch(InterruptedException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public void disconnect() {
		semaphore.release();
	}
	
	public int getNumPermitsAvailable() {
		return semaphore.availablePermits();
	}
}