66.

Overview

When a program leaks or frees resources too early—resources such as memory, files, or database connections—a Split Cleaner may be the problem. We look at how the resource is managed as a potential cause.

One key feature of Java is that storage is automatically managed, saving the programmer from the bug-prone task of freeing memory after it has been used. Nevertheless, many programs still have to manipulate resources that must be explicitly freed after use. As is true in manual storage management, there are pitfalls that a programmer can encounter when managing resources in this way.

When managing a resource such as a file or a database connection, it is necessary to free the resource once you're done with it. Of course, on any given execution of the code, you want to obtain and free the resource exactly once. There are a couple of ways you could go about doing this:

  • Obtain and free the resource in the same method. This way, you can guarantee that each time the resource is obtained, it is also freed.

  • Trace through each possible execution path of the code. This way, you have to check that the resource is eventually freed in each case.

The second option is problematic. Because your code base will inevitably grow, another programmer who is not familiar with your code may add another execution path in which the resource is not freed, resulting in resource leakage.

I call bugs that fit this pattern Split Cleaners because the clean up code for the resource is split along the various possible execution paths. Because the clean up code along each path is likely to be identical, most Split Cleaners are also examples of Rogue Tiles (see Chapter 7).

We can summarize this bug pattern as follows:

  • Pattern: Split Cleaner.

  • Symptoms: A program that improperly manages resources, either by leaking them or by freeing them too early.

  • Cause: Some execution paths of the program do not free the resource exactly one time as they should.

  • Cures and Preventions: Move the code that handles clean up into the same method that obtains the resource.



Bug Patterns in Java
Bug Patterns In Java
ISBN: 1590590619
EAN: 2147483647
Year: N/A
Pages: 95
Authors: Eric Allen

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net