Home  Synchronization and concurrency  wait/notify  final  volatile  synchronized keyword  Java threading  Deadlock (and avoiding it)  Java 5: ConcurrentHashMap  Atomic variables  Explicit locks  Queues  Semaphores  CountDownLatch  CyclicBarrier

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.)

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.

Article written by Neil Coffey (@BitterCoffey).

Software

 LetterMeister (word puzzle game for iPhone)
 Currency Quoter (currency converter/predictor)
 French Vocab Games for iPhone/iPad
 Vocabularium: create Spanish vocab podcasts


Java programming articles and tutorials on this site are written by Neil Coffey (@BitterCoffey). Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Neil Coffey 2014. All rights reserved.