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:
- we create a pool which can hold up to some maximum number
of resources; at any one time, the pool knows how many resources it has created
(in other words, if it is "allowed to create more");
- when a thread needs one of the resources, it "requests" one from the pool;
when it has finished with it, it "returns" it to the pool;
- if a resource is available in the pool, it is returned immediately;
- if no resource is available, but the maximum number of resources has not
yet been given out, then a new one is created and returned immediately;
- else, the pool waits for one of the other threads holding a resource
to return it to the pool before giving it to the waiting thread;
- ideally, we want a thread to only wait for a resource for so long before
giving up. (That is, we don't want a thread to wait for ages if the
server is just "too busy" at the moment: it may be better to display a "server busy"
message to the client after a couple of seconds than make it hang for a long time.)
On the next page, we look at the general pattern for
using Semaphore to
control a reource pool such as a database connection pool.