2. You will learn that
• There are memory leaks in Java
• Garbage collector can be a bottleneck
• Thread locks are more common than you
think
• You can automatically detect these problems
3. How can JVM leak memory?
• Static fields are not gc’d
• Thread-local + thread pools
• Application scope
• Complex bi-directional refs
• OS resource handles: files, sockets, db
4. Static fields
class Forever {
// Unless you explicitly unload this class
// GC will not touch it
static final ArrayList list = new ArrayList(1000);
}
5. Thread-local
public void doFilter(ServletRequest req, ServletResponse res){
myThreadLocal.set(new BigLeak());
// thread goes back to the thread pool
// with the big leak planted
chain.doFilter(req, res);
}
7. Bi-directional relationships
org.w3c.dom.Document doc = readXmlDocument();
org.w3c.dom.Node child =
doc.getDocumentElement().getFirstChild();
doc.removeNode(child);
doc = null;
// child still has reference to doc. No GC for the doc.
8. OS resources
try {
Connection conn = ConnectionFactory.getConnection();
...
conn.close();
} catch (Exception e) {
// oops, connection is still open
}
10. GC Pause
• Full garbage collection stops the world!
• Heavily utilized heap = frequent pauses
• Complex dependency graph = long pause
• Lots of long living objects = long pauses
11. Heap size vs pause
source: performanceterracotta.blospot.com
13. Is it really our problem?
QUESTION:
Does it impact our business if the system
regularly suspends itself for several seconds?
BETTER QUESTION:
What is the level of unresponsiveness we allow
in our system?
As low as possible = bullshit answer
14. No measurement = no answer
pauses for about half a second 2-3 times a minute
15. GC friendly programming
• Avoid long living objects – minor gc is faster
• Avoid mutable objects – questionable…
• Design your classes small – faster compaction
• Avoid complex dependency graphs
• NEVER call System.gc() – disturbs optimal plan
27. Is there really no other way?
newBalance = oldBalance.deposit(amount)
// no sync needed
28. Share immutable objects
public class Address {
public final String streetName;
public final int aptNo;
public final String zipCode;
public Address (String name, int apt, String zip){
// initialize all the fields
}
}