Member-only story

Effective Java! Prefer try-with-resources

Kyle Carter
3 min readDec 26, 2020

Today we have a topic right in line with what we talked about last week. Last week the topic was on finalizers and cleaners. One of the common uses for these is to clean up resources. In this blog post we will go into a little more detail of the better way we hinted at at the end of the previous post.

There are many resources that for one reason or another need to be manually closed after use. This often is accomplished by using a close method on the object. We of course don't want to leak resources or leave items in a half handled state. This being the case we may consider putting the close method in a finally block. For example:

static List<Object> getDbValues() {
EntityManager em = getEntityManager();
try {
return em.createNativeQuery("SELECT * FROM myTable").getResultsList();
} finally {
em.close();
}
}

This will work just fine, it doesn’t even look that bad. It does get more confusing and error prone as we add more resources.

static List<Object> getDbValues() {
OutputStream output = getOutputStream();
InputStream input = getInputstream();
try {
try {
// do work
} finally {
input.close();
}
} finally {
output.close();
}
}

This is starting to get more gross and hard to follow. Did I even do it right? I’m not convinced. It can be easy to mess up. The author even admits that he had this pattern messed up in one of his books for years and no one realized. Even with the correct code…

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet