Subscribe: The Daily WTF
Preview: The Daily WTF

The Daily WTF

Curious Perversions in Information Technology

Last Build Date: Wed, 29 Mar 2017 21:32:54 GMT


CodeSOD: Prepared for the Real World

Wed, 29 Mar 2017 10:30:00 GMT

Usul is taking a college course on Java programming, and it’s doing an excellent job preparing him for the real world. Already, he’s been forced to cope with someone who knows one true fact and has run off to apply it in the dumbest way possible. This would be his professor. Our true fact is this: A Java PreparedStament object, used for running database queries, should be closed after use. This returns its connection to the pool and frees any resources the statement was using. You should do this, and you should do it as soon as you’re done with your connection. Now, putting a call to stmt.close() in every finally block was just too much for Professor McCloseypants to deal with. So he provided this “convenience” object to deal with that problem. It’s a lot of code, so we’re going to do this in pieces. First, let’s look at the declaration: public class ClosingPreparedStatement { … } Now, remember, the purpose of this class is to do everything a PreparedStatement does, but add a self-closing behavior. Thus, the first problem here is that it doesn’t have an extends or implements declaration, so that it could share a common interface with PreparedStatements. /** * */ public static boolean somethingFinalized = false; Remember, this is a professor, providing this code as a model of what his students should be doing. For the capstone course, required for graduation. Now, this is a wrapper around a PreparedStatement, so guess how most of the methods work… /** * Just delegates * * @param arg0 delegate's parameter * @param arg1 delegate's parameter * @return the delegates return value * @throws SQLException if delegate throws it */ public int executeUpdate(String arg0, String[] arg1) throws SQLException { return stmt.executeUpdate(arg0, arg1); } Oh yeah. There are almost 1,300 lines of code in this file, and yes, they’re pretty much all like this. So, with all of that, how does this magical self-closing statement work? /** * Closes the internal statement and delegates * * @throws Throwable if the delegate throws it */ protected void finalize() throws Throwable { try { stmt.close(); somethingFinalized = true; } finally { super.finalize(); } } He put it in the finalize method. If you’re not intimate with Java’s memory management, keep in mind: the finalize method is called by the garbage collector [Advertisement] Release! is a light card game about software and the people who make it. Play with 2-5 people, or up to 10 with two copies - only $9.95 shipped! [...]