Year Of Security for Java – Week 29 – Manage Resources

No Gravatar

What is it and why should I care?
Resource management has been an issue in programming for a very long time, and it’s one of those issues that affects the A (Availability) of the classical C-I-A triad in information security. It’s effectively where you gain access to some (generally expensive) resource (think database connection, file handle, etc.), and then don’t properly return access, hence you don’t release the associated resources (disk space, memory, file handles, network connectivity, etc.)

While not as high-profile as losing your user account database with all your passwords stored in roughly the equivalent as ROT-13 (the current flavour of the month in the security news), it can be pretty embarrassing to have your site fall over constantly due to resource leaks. Crashing, or at least instability, is the inevitable outcome of poor resource management. It’s also not fun being the guy or gal that gets to restart the server every night at 2AM to make sure it will work without crashing the next day (yes, I have a fried who used to do this).

What should I do about it?

In order to prevent resource leaks, you need to properly release resources when they are no longer needed. In Java, that can look like a few different things.

1. finally block
The traditional way to close resources in Java is to use the finally block that’s provided by the language. This is a fairly simple process once you know the idiom. It essentially looks like the following.

BufferedReader bufferedReader = null;
FileReader fileReader = null;

try {
    String line;
    fileReader = new FileReader("/tmp/myfile.txt");
    bufferedReader = new BufferedReader(fileReader);

    while((line = bufferedReader.readLine()) != null) {
	System.out.println(line);
    }

} catch(Exception e1) {
    e1.printStackTrace();
} finally {
    if(fileReader != null) {
    	try {
	    fileReader.close();
    	} catch(Exception e2) {
	    e2.printStackTrace();
    	}
    }

    if(bufferedReader != null) {
    	try {
	    bufferedReader.close();
    	} catch (Exception e2) {
	    e2.printStackTrace();
    	}
    }
}

Here we read a file, and print out each line. Notice that a good chunk of our code is devoted to resource management. However, if you generified this method by parameterizing the filename and returning a string representing the file contents, then you could make the method reusable. This is exactly what many file reader style utilities do.

2. try-with-resources
So why do people not close resources? Well, it’s part ignorance of the issue, copying bad code snippets and laziness from what I’ve seen. What would be really nice is if the language itself gave you a way to get around this issue by making it automatic. Well in Java 7, after many, many requests for the functionality, it’s finally been added as the try-with-resources statement.

Try-with-resources is only available in Java 7 and later, so you can’t use it if you’re on an older version of Java. However, if it is available to you, it’s a nice little abstraction of syntactic sugar that allows you to push the resource management grunt work to the language itself. Below is a modified version of our initial code using try-with-resources.

try (FileReader fileReader = = new FileReader("/tmp/myfile.txt");
     BufferedReader bufferedReader = new BufferedReader(fileReader)
) {
	String line;

	while((line = bufferedReader.readLine()) != null) {
	    System.out.println(line);
	}

} catch (Exception e) {
	e.printStackTrace();
} 

As you can see, the try-with-resources version is much shorter, cleaner and accomplishes the same thing. That’s generally a good thing when it comes to code.

3. Use and create libraries with proper resource management
There are good examples of open source libraries that do this effectively. For instance, Hibernate and Spring both do proper resource management for database access. Just by using their libraries in the recommended configuration, you are accessing and releasing resources properly.

In addition to using open source libraries, you’ll almost always find some utilities classes or libraries in applications related to resource management (think FileUtils, StreamUtils, DbUtils, etc.). If you build your resource utilization code into reusable libraries that perform proper management, then all your applications benefit.

In conclusion, resource management is one of those issues which doesn’t get a lot of attention, but that can be critical to the stability of your application. Also, we showed that it’s pretty easy to properly manage resources in Java if you know what to do, particularly when you move that functionality into reusable libraries.

References
———–
http://www.mkyong.com/java/try-with-resources-example-in-jdk-7/
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Be Sociable, Share!

Technorati Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *