When you find a problem, fix it and start over. Patching one leak can solve
others as well. Many leaks are interrelated—sometimes in surprising ways—
and you'll find it much easier to fix links one at a time than to try to solve
them all with a single pass.
Fixing leaks usually turns out to be relatively easy after you've identified a
problem. You must make the object unreachable by using one of the tech-
niques described in this chapter. These techniques can make an object
unreachable, and thus a candidate for garbage collection:
Fixing Java application memory leaks
When an object with a long life cycle maintains a reference to an object with a short
life cycle, we have the potential for a memory leak. These possible fixes remove refer-
ences to make an object unreachable and eligible for garbage collection.
Remove the object reference directly by setting it to another value.
Remove an object from a collection.
Weaken the references using Java reference objects.
Shorten the life cycle of the referent.
Shorten the life cycle of the object.
Remove the object from the code.
Refactor the code.
Protect against the problem for the future
When coding problems occur, you should examine the cause. If the problem is
an isolated case of programming error, no further action may be necessary.
These steps will help keep the problem from occurring in the future:
Add to the test suite to make sure that the new case is covered. This will
ensure that if the problem crops up again through poor change control
or cut and paste, it will be found.
If the problem has occurred in the past, an antipattern should be docu-
mented and shared.
If the antipattern or solution lends new significant insight, it should be
published at some level. Publishing paths can be as focused as emails to
peers or presentations in department meetings, and as broad as writing a
book or speaking at a conference.
Antipatterns work best when we establish a pattern, solve a problem in a gen-
eral way, and disseminate the wisdom.