Concurrent applications usually have a pool of resources. For example, we have thread pooling and connection pooling. Creating and destroying such a connection as we go is costly. Instead, a pool is created, and whenever the app needs a resource, it goes and asks the pool.
The pool is configured to hold a certain number of these resources. For example, 20 database connections or 355 threads. When the demand is high, the pool could get exhausted. Unless some resources are released, the requesting thread should be put to sleep:
A semaphore would come, handy in implementing such scenarios. The semaphore is initialized with an initial capacity, cap, representing the configured pool size:
The following listing shows a semaphore implementation:
public class Semaphore {
private final int cap;
private int count;
private final Lock lck;
private...