Garbage collection · Topic 4 of 6
Memory leaks
Definition​
Java frees unreachable objects, so a "leak" means objects you no longer need that are still reachable, for example items added to a static list that is never cleared. Keep caches bounded and remove listeners and entries when you are done.
Example code​
An ever-growing static list, and a bounded cache instead
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
class Demo {
static final List<byte[]> leaky = new ArrayList<>(); // static: reachable for the whole run, never cleared
static class BoundedCache<K, V> extends LinkedHashMap<K, V> {
private final int max;
BoundedCache(int max) { super(16, 0.75f, true); this.max = max; }
@Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > max; }
}
public static void main(String[] args) {
for (int i = 0; i < 1_000; i++) leaky.add(new byte[1024]); // every item stays reachable: this grows forever
System.out.println("leaky list size: " + leaky.size());
BoundedCache<Integer, byte[]> cache = new BoundedCache<>(100);
for (int i = 0; i < 1_000; i++) cache.put(i, new byte[1024]);
System.out.println("bounded cache size: " + cache.size()); // old entries were removed
}
}
// Output:
// leaky list size: 1000
// bounded cache size: 100
Finished this page? Track your progress (saved only in your browser).