Minimizing memory Leaks in your java j2ee applications | Techartifact

Enough of ADF.Lets talk about memory leak in java today in our application.How we can reduce it.

Java’s memory managmement (i.e Garbage collectionGarbage collection -how it works) prevents lost references and dangling references but it is still possibilities to create memory leaks in other ways. If the application run with memory leaks for long duration ,you will get the error java.lang.OutOfMemoryError.

In java ,typically the memory leak occur when an object of a longer lifecycle has references to the objects of a short life cycle. This prevents the
object with short life cycle being garbage collected. The developer must remember to remove the references to the short lived object from the long-lived objects.Objects with same life cycle do not cause any problem because the garbage collector is smart enough to deal with the circular references.

-> Java collection class like HashTable, ArrayList etc maintain references to other objects.So having a long life cycle ArrayList pointing to many . . short-lifecyle objects can cause memory leaks.

-> Commonly used singleton Design pattern can cause memory leaks.Singleton typically have a long lifecycle. If a singleton has an arrayList or a HashTable then there is potential for memory leaks.

-> 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 resources in the finalize method or try {} block instead of finally() block can cause memory leaks.