However, this question is far too crude to get a completely correct answer here. I have only shown you common behavior patterns.
What is a memory leak?
A Memory Leak is a situation when there are objects present in the heap that are no longer used, but the garbage collector is unable to remove them from memory and, thus they are unnecessarily maintained. A memory leak is bad because it blocks memory resources and degrades system performance over time.
What causes memory leaks in Java?
The first scenario that might cause a Java memory leak is referencing a heavy object with a static field. We created our ArrayList as a static field – which will never be collected by the JVM Garbage Collector during the lifetime of the JVM process, even after the calculations it was used for are done.
Symptoms of a Memory leak:
Works fast at first, but slows over time.
- Works fine with small data sets, severe performance issues with large data sets
- Ever increasing Old-Generation memory usage in your JVM
- Out-of-Memory Heap errors in your JVM
- Spontaneous crashes.
Common memory leaks:
File/Text buffers not closed.
Hash maps keeping references alive if equals() and hashcode() are not implemented, e.g.
import java.util.Map;
public class MemLeak {
public final String key;
public MemLeak(String key) {
this.key = key;
}
public static void main(String args[]) {
try {
Map map = System.getProperties();
for(;;) { map.put(new MemLeak("key"), "value"); }
}
catch(Exception e) { e.printStackTrace(); }
}
}
How to fixing them?
There are two approaches. The first is a 'quick fix' attempt. If that fails then you'll have to go down the long road.
- Quick fix: Eclipse Memory Leak Warnings (catches some leaks)
- Manually disable & enable parts of your code and observe memory usage of your JVM using a JVM tool like VisualVM (or Jconsole, or Thermostat).