Controlling resources with the Semaphore class in Java 5

A common situation in server applications is that multiple threads compete for resources which are in some way limited in number: either because they are finite, or because (e.g. in the case of database connections) although we could theoretically have a large number, they are expensive to create and hold on to unnecessarily. A typical situation is this:

The Semaphore class was introduced in Java 5 to aid in creating this type of functionality.

On the next page, we look at the general pattern for using Semaphore to control a reource pool such as a database connection pool.