Upload
gautam-singh
View
52
Download
2
Embed Size (px)
Citation preview
Finalizers –The not so Good, the Bad and the Ugly
A Garbage Collection Saga
Gautam Singh www.livemykarma.com @singhkgautam
Fun Day
Work Day
Analyzing Thread Dump
What is Finalizer?
• Method on Object class. protected void finalize() throws Throwable
• Used to perform postmortem cleanup.
• Called by GC after an object is dead.
• Called by Finalizer thread
Finalizable Object life Cycle
Benchmark Results
Avg. time(ns) per Object creation
7X – 600X slow
Avg. Time(ms) spend in GC
50X – 200X more
Allocation(Bytes) Per Instance
Around 3X
Benchmarking library: JMH http://openjdk.java.net/projects/code-tools/jmh/ GitHub Repo: https://github.com/LiveMyKarma/Finalizer
Problem Class
Load Test Result (Before)
Load Test Result (After)
Problem with Finalizers
Finalizers are unpredictable, often dangerous, and generally unnecessary
Effective Java – Joshua Bloch
Dead Object Resurrection(Bad)
Dead Object Resurrection(Bad)
Increase Allocation Cost(Bad)
Allocation(Bytes) Per Instance
Around 3X
Cause more GCs(Ugly)
No Guarantee, when called (Ugly)
No Guarantee (Example)
Make object concurrent(Ugly)
When to use Finalizer(Not so Good)
• De-allocation of non-memory resources for objects
– With hard to predict lifetimes
– For which cleanup is not time-critical
• Safety net when client forget to call explicit clean-up method.
– Logging
How to avoid Finalizers Pitfalls
Do you really need finalizer?
Utilize Lifecycle methods, if available
Provide explicit termination method.
Reduce data overhead(Before)
Reduce data overhead(After)
Utilize Cache or Object pool
Image: http://www.birdsandblooms.com/birding/birding-basics/bird-behavior-caching-food/
References
• Effective Java (2nd Edition) By Joshua Bloch https://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683
• The Garbage Collection Handbook: The Art of
Automatic Memory Management By Richard Jones, Antony Hosking, Eliot Moss
http://gchandbook.org/
• Benchmark Source https://github.com/LiveMyKarma/Finalizer
I think my eyes are getting better. Instead of a big dark blur, I see a big light blur.
HAN SOLO, Star Wars Episode VI: Return of the Jedi
Questions?