This document discusses memory management in Java and analyzing memory usage. It describes the sizes of primitive data types and object headers in Java. It also covers garbage collection, memory leaks if references are not properly cleared, and solutions like SoftReference and WeakReference to help prevent memory leaks. Tools for analyzing heap dumps are presented, including Eclipse Memory Analyzer, which can show histograms of object instances, dominator trees, and paths to GC roots to help debug memory issues.
14. SoftReference
1. SoftReference<List<Foo>> ref = new SoftReference<List<Foo>>
(new LinkedList<Foo>()); // create some Foos, probably in a loop
2. List<Foo> list = ref.get();
3. if (list == null) throw new RuntimeException("ran out of memory");
4. list.add(foo);
15. WeakReference
1. WeakReference<List<Foo>> ref = new WeakReference<List<Foo>>
(new LinkedList<Foo>()); // create some Foos, probably in a loop
2. List<Foo> list = ref.get();
3. if (list == null) throw new RuntimeException("ran out of memory");
4. list.add(foo);
16. PhantomReference
1. PhantomReference<List<Foo>> ref =
new PhantomReference<List<Foo>>(new LinkedList<Foo>(), new ReferenceQueue<List<Foo>>());
// create some Foos, probably in a loop
2. List<Foo> list = ref.get(); // always return null
24. GC Roots
The so-called GC (Garbage Collector) roots are objects special for garbage collector. Garbage collector collects those objects
that are not GC roots and are not accessible by references from GC roots.
There are several kinds of GC roots. One object can belong to more than one kind of root. The root kinds are:
● Class - loaded class. Classes can hold objects via static fields.
● Alive Threads
● Stack Local - local variable or parameter of method.
● Finalizer Queue Entry - object scheduled for finalization.
● GC Handle - provides a means for accessing a managed object from unmanaged memory.
● Other - objects hold from garbage collection by CLR for other reasons.