Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Build your own ObjectPool in Java to boost app speed

Increase the speed of your applications while reducing memory requirements

  • Print
  • Feedback

Page 3 of 3

boolean validate( Object o )
{
   try
   {
      return( ! ( ( Connection ) o ).isClosed() );
   }
   catch( SQLException e )
   {
      e.printStackTrace();
      return( false );
   }
}


That's it for internal functionality. JDBCConnectionPool will allow the application to borrow and return database connections via these incredibly simple and aptly named methods.

public Connection borrowConnection()
{
   return( ( Connection ) super.checkOut() );
}
public void returnConnection( Connection c )
{
   super.checkIn( c );
}


This design has a couple of flaws. Perhaps the biggest is the possibility of creating a large pool of objects that never gets released. For example, if a bunch of processes request an object from the pool simultaneously, the pool will create all the instances necessary. Then, if all the processes return the objects back to the pool, but checkOut() never gets called again, none of the objects get cleaned up. This is a rare occurrence for active applications, but some back-end processes that have "idle" time might produce this scenario. I solved this design problem with a "clean up" thread, but I'll save that discussion for a follow-up article. I will also cover the proper handling of errors and propagation of exceptions to make the pool more robust for mission-critical applications.

I welcome any comments, criticisms, and/or design improvements you may have to offer.

About the author

Thomas E. Davis is a Sun Certified Java Programmer. He currently resides in sunny South Florida, but suffers as a workaholic and spends most of his time indoors.

Read more about Core Java in JavaWorld's Core Java section.

  • Print
  • Feedback

Resources