How would you go about minimizing memory leaks in your Java/J2EE application?

Java’s memory management (i.e. Garbage Collection) prevents lost references and dangling references but it is
still possible to create memory leaks in other ways. If the application runs with memory leaks for a long duration
you will get the error java.lang.OutOfMemoryError.
In Java, typically the memory leak occurs when an object of a longer life cycle has a reference to the objects
of a short life cycle. This prevents the objects with short life cycle being garbage collected. The developer must
remember to remove the reference to the short-lived objects from the long-lived objects. Objects with the same life
cycle do not cause any problem because the garbage collector is smart enough to deal with the circular references

1. Java Collection classes like Hashtable, ArrayList etc maintain references to other objects. So having a long
life cycle ArrayList pointing to many short-life cycle objects can cause memory leaks.
2. Commonly used singleton design pattern  can cause memory leaks. Singletons
typically have a long life cycle. If a singleton has an ArrayList or a Hashtable then there is a potential for
memory leaks.
3. Java programming language includes a finalize method that allows an object to free system resources, in
other words, to clean up after itself. However using finalize doesn’t guarantee that a class will clean up
resources expediently. A better approach for cleaning up resources involves the finally method and an explicit
close statement. So freeing up the valuable resource in the finalize method or try {} block instead of finally {}
block can cause memory leaks.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s