
49
What Does GC Mean to You?
•Ideally, nothing
–It should make your life easier
–And shouldn’t affect performance too much
•May even give better performance than you’d have
with explicit deallocation
• If GC becomes a problem, hard to solve
–Not much control over it
50
Increasing Memory Performance
•Don’t allocate as much memory
–Less work for your application
–Less work for the garbage collector
–Should improve performance
•(Why only “should”?)
•Don’t hold on to references
–Null out pointers in data structures
–Or use weak references
51
Find the Memory Leak
class Stack {
private Object[] stack;
private int index;
public Stack(int size) {
stack = new Object[size];
}
public void push(Object o) {
stack[index++] = o;
}
public void pop() {
return stack[index--];
}
}
–From Haggar, Garbage Collection and the Java Platform Memory Model
52
Bad Ideas (Usually)
• Calling System.gc()
–This is probably a bad idea
–You have no idea what the GC will do
–And it will take a while
•Managing memory yourself
–Object pools, free lists, object recycling
–GC’s have been heavily tuned to be efficient
53
java.lang.ref
• Package that lets you interact with GC
–If there’s a strong (normal) reference to an
object, GC will consider it live
–Can use java.lang.ref to make references to
object that “don’t count”
public abstract class Reference {
void clear();
public Object get();
...
}
54
SoftReference
•Constructor SoftReference(Object o)
–Make a soft reference to object o
–Access using get() method
•GC may free object if
–Only soft, weak, or phantom refs to it
•No strong refs
•GC invokes clear() on SoftRef if freed