Memory leaks are blocks of allocated memory that the program no longer references. Leaks waste space by filling up pages of memory with inaccessible data and waste time due to extra paging activity. Leaked memory eventually forces the system to allocate additional virtual memory pages for the application, the allocation of which could have been avoided by reclaiming the leaked memory.

Tips:

  • Pair code that handles allocation and freeing of resources as closely together as possible, preferable in the same method.
  • With collections, objects that are added should be removed as well.
  • Take your application to a development environment and run it inside a memory profiler.

It is almost impossible to improve the performance of your code if your application is impacted by memory leaks.  Memory leaks can be in either Java or native code.  In native code, memory leaks are caused by the programmer forgetting to free a memory block.  Java memory leaks are often caused by saving an object reference in a class level collection and forgetting to remove it at the proper time. 

There are also other kinds of problems with managing resources that impact performance, such as not closing JDBC Statements/ResultSets in a finally block (many JDBC drivers store a Statement reference in the Connection object).  Fixing memory/resource leaks in the application not only has a great impact on performance but also system stability, as you will consume fewer resources. 

Ref:
Reference Objects and Garbage Collection
Handling memory leaks in Java programs
Memory Leaks
Overview of memory leaks
Launching the Java application VM manually when debugging

Advertisements