dagblog.
← Archive

A JDBC memory leak for 5.50


Fancy a little memory leak that eventually makes your application crash with java.lang.OutOfMemory? You’ll need the following ingredients.

  • Code that talks to a database through JDBC
  • A database connection pool

The most important ingredient, though, is the following pattern.

PreparedStatement pstmt = null;

try {

Connection con = //ziskej DB connection z poolu

 pstmt = con.prepareStatement(“select …”);

 

 //udelas dootaz, zpracujes bysledky

 //a pak vytvoris novy statement, bez toho

//aniz by si uzavrel ten predchozi



 pstmt = con.prepareStatement(“select …”);



} finally {

 //ve finally sice zaviras statement,

//ale to se jedna samozrejme az o tu 

 //druhou instanci

 DatabaseUtils.closeStatement(con, pstmt);

}

I’ll explain why the memory leak occurs, since it may not be obvious. Even though pstmt is a local variable and it looks like the garbage collector could clean up the object it refers to, it can’t. The statement is still referenced by the database connection (con).

Because the connections are pooled, unclosed statements sit around until they take up enough memory to cause a java.lang.OutOfMemory. At least, that’s what I experienced with the Oracle JDBC driver.

One final reminder. The best defense is prevention. For example,
let something else manage the statement for you. See The Template Method Design Pattern and Its Use in JDBC.

Medium version

Related articles

Related CZ Podcast episodes