One of the most common mistakes that occurs when using a resource pool is forgetting to check resources back in. This leads to resource leaks, a condition where resources disappear faster than expected, until no resources are left and the application locks up waiting for resources that never appear.

The most obvious way to avoid resource leaks is to make sure that for every checkOut you have a corresponding checkIn. This should be a fairly easy error to catch, because forgetting to do this causes you to run out of resources fairly quickly.

A subtler problem arises in the case where an exception occurs, terminating the operation and bypassing the checkIn call. If exceptions occur infrequently, it takes longer for your application to run out of resources, and it is far harder to debug because your application appears to lock up at random intervals.

The way to avoid this problem is to put the checkIn call inside of a finally statement, thereby ensuring that no matter what happens, the checkIn call is still made.

So the code from the previous example looks like this:

ResourceObject resource = null;
try {
  // Get a resource
  resource = getResourcePool ().checkOut (getAbsoluteName ());
  ReallyExpensiveObject obj = (ReallyExpensiveObject)
    resource.getResource ();

  ...
}
catch (ResourcePoolException exc) {
  if (isLoggingError ()) logError (exc);
}
finally {
  if (resource != null) getResourcePool ().checkIn (resource);
}

Remember that this is not an optional coding style. Failing to program in this manner is almost guaranteed to cause your application to lock up at random, unexpected intervals.