Thursday, November 02, 2006

When Garbage Collection isn't Enough

There is frequently an error that people make when allocating resources. Everyone seems to understand that you use a try/finally block but how to do it is usually unclear. Should you put all the resource deallocation in one finally block? How do you handle the exception that maybe thrown attempting to deallocate the resource?

I've previously advocated using a non-final assignment and then checking in the finally block if object is not null and then closing it. The better way is:
final Connection conn = ...;
try{
...
} finally {
close(conn);
}
This idiom is detailed here. It gives reasons behind using this idiom and the rule of thumb: "place one "try-finally" directly after each resource allocated".

This was written in 2005 based on a previous Javalobby thread. I continue to see resource leaks caused by not closing resources correctly. I know of people who have made considerable money consulting to fix these kinds of bugs in large systems which I find fairly depressing.

No comments: