SlideShare a Scribd company logo
1 of 23
Diagnosing HotSpot JVM Memory Leaks
with JFR and JMC
Mushfekur Rahman
Software Engineer II
Today We’ll Talk About...
● Java Reference Types
● Understanding GC Reachability
● Memory Leak and java.lang.OutOfMemoryError
● Brief Introduction to JFR and JMC
● Few Classic Leak Scenarios
Java Reference Types
● What about it?
○ How do we create a reference to an object?
Car c = new Car();
● This is not the only way we can create references *newsflash*
● Java offers four types of references
1. Strong
2. Soft
3. Weak
4. Phantom
GC Reachability
● Let’s be a little hypothetical, what does GC do?
○ Simulate a finite memory space as infinite
● A common misunderstanding
○ GC collects unused/dead objects and reclaims memory space occupied by them
○ It’s actually the exact opposite
■ GC marks live objects
■ Reclaims everything else
GC Reachability (contd.)
GC Reachability (contd.)
● Eligibility of an object to be GC’d depends on references
● GC algorithms traverse objects starting from GC root
○ GC roots
■ Source of Object trees
■ Possible candidates are active threads, and it's local variables, static variables
and JNI references
○ All the objects that are reachable from GC root are marked as alive (not eligible for GC)
● If there’s no strong reference to an object, it’s going to be collected
Revisiting JVM Memory Management
Behold The OutOfMemoryError !
● It’s not that generic as you might’ve thought!
● Heap
○ Exception in thread "main": java.lang.OutOfMemoryError: Java heap
space
○ This is what today’s session is mostly about
● PermGen
○ Exception in thread "main": java.lang.OutOfMemoryError: PermGen space
○ We’ll talk about PermGen leaks in another session
● Doesn’t always mean there’s a memory leak
○ Fragmentation
○ HotSpot VM throws OutOfMemoryError in case of excessive GC activities (e.g. 90% of
execution time is being used for GC while 2% memory is being used)
Wait a minute...
● So, we are fine as long as there’s no OutOfMemoryError?
○ Not really!
○ In fact, little unnoticed leaks are both decisive and vicious.
● What all these has to do with application performance?
○ GC is essential but expensive
○ GC is one of the biggest contributor to the overall latency in JVM applications
○ The less memory used, the less GC
Java Mission Control
● Set of powerful monitoring and diagnosis tools that comes with Oracle JDK
● Two main parts
○ JMX Console
■ For monitoring JVM in real time
○ Java Flight Recorder
■ For collecting data about JVM (profiling)
● Can monitor JVM instances both local and remote
○ Event triggers
○ Execute troubleshooting commands on target JVM
● Supports plugins
○ For additional functionalities (e.g. heap dump analysis, DTrace recording etc.)
● Free for development use
Java Flight Recorder
● Flight Recorder
“A flight recorder, commonly known as a black
box, although it is now orange-coloured, is an
electronic recording device placed in an aircraft
for the purpose of facilitating the investigation of
aviation accidents and incidents.” - Wikipedia
Fig. An actual aircraft Flight Recorder
Java Flight Recorder (contd.)
● High performance event recorder
○ Built into the runtime
● Recordings are stored as binary chunks
○ Very detailed (records everything according to settings)
○ Self contained and self describing
● Very low overhead (<=1% according to Oracle)
○ Can keep it running always
○ Dumps can be taken from time to time using JVM debugging commands (e.g. jcmd)
Java Flight Recorder (contd.)
● Recording Types
○ Continuous Recording
■ Have no end time
■ Must be explicitly dumped
○ Time Fixed Recordings (a.k.a Profiling Recordings)
■ Events will be captured within the specified timeframe
■ Will be automatically dumped in the specified location
JFR Setup
● Start JVM with the following flags
-XX:+UnlockCommercialFeatures -XX:+FlightRecorder
● For remote profiling add JMX related com.sun.management flags
● Additional parameters can be passed with -XX:StartFlightRecording
● Templates can be specified with a settings parameter
○ Templates can be created using JMC
○ Default template location $JAVA_HOME/jre/lib/jfr
○ Can only be used with JRockit or HotSpot (7u40 or later)
● *If there’s any* disable other profiling tool that does instrumentation (e.g.
XRebel)
Recording Events
● Default Recording
○ Starts a continuous recording
○ defaultrecording parameter is need to be added when starting JVM
○ dumponexit and dumponexitpath parameters can also be used with it
○ To get more info on what’s going on we can change log level
-XX:FlightRecorderOptions=loglevel=trace
○ Example: The following will start a default recording
-
XX:FlightRecorderOptions=defaultrecording=true,dumponexit=true,dumponexi
tpath=<path>
Recording Events (contd.)
● Creating records on the fly
○ Need to pass signal in target JVM (using jcmd)
○ Available commands: JFR.start, JFR.check, JFR.stop, JFR.dump
○ Command format:
jcmd <pid> <command> <parameters>
○ Starting a recording
jcmd 4609 JFR.start name=DemoRecording settings=profile
delay=20s duration=5m filename=/home/demorecording.jfr
Back To Memory Leak!
Common Pitfalls
● Non-static Inner Classes
○ Inner class has an implicit reference to the containing class
○ Isn’t supposed to live longer than the container class
○ What if an outer context holds a reference to the inner class?
■ Due to the implicit strong reference outer class cannot be GC’d
public class OuterClass {
/**
* Outer class contents
*/
public class InnerClass {
/**
* Inner class contents
*/
}
}
Common Pitfalls (contd.)
● Flyweight Pattern
○ Structural design pattern aims to reduce cost of object creation
○ Reusing already existing objects by maintaining an object pool
○ Two states in every object
■ Intrinsic: Shareable values
■ Extrinsic: Non shareable values. Created and/or destroyed based on the client object
actions.
Common Pitfalls (contd.)
● JSP Tag Pooling
○ Servlet containers cache tag instances for performance reason
○ States goes back to the pool along with tag instances
○ Wait... it’s not just about heap leak
■ What if you have logic based on current state?
● Kaboom!
○ Should cleanup instance variable states after use
○ Example
Common Pitfalls (contd.)
● Stateless Session Beans (Stateless EJBs)
○ Conversational state with a client is not stored
○ However, values of instance variables is held when returning in pool
○ Same as JSP Tag pooling it’s not just about memory
○ Should cleanup instance variable states, unless required
Common Pitfalls (contd.)
● ThreadLocal instances
○ Lifecycle bound to the owning thread
○ Typical multithreaded services use thread pools
■ Threads gets re-used
○ What if you forget to cleanup after the thread finishes it’s work?
● Implicit leaks
○ Autoboxing in a loop
○ Serializing/cloning/copying complex object graphs
Additional Resources
● Troubleshooting Guide for HotSpot VM (Chapter 3)
● Using Java Flight Recorder (JavaOne ‘15)
● Java Mission Control for Earthlings (Devoxx France ‘15)
● Running Java Flight Recorder

More Related Content

What's hot

Transactional Memory
Transactional MemoryTransactional Memory
Transactional MemoryYuuki Takano
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Tools in action jdk mission control and flight recorder
Tools in action  jdk mission control and flight recorderTools in action  jdk mission control and flight recorder
Tools in action jdk mission control and flight recorderJean-Philippe BEMPEL
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overviewSergey Stupin
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageAsankhaya Sharma
 
Observer pattern with Stl, boost and qt
Observer pattern with Stl, boost and qtObserver pattern with Stl, boost and qt
Observer pattern with Stl, boost and qtDaniel Eriksson
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresHDR1001
 
RPC in Smalltalk
 RPC in Smalltalk RPC in Smalltalk
RPC in SmalltalkESUG
 
Logitoring - log-driven monitoring and the Rocket science
Logitoring - log-driven monitoring and the Rocket scienceLogitoring - log-driven monitoring and the Rocket science
Logitoring - log-driven monitoring and the Rocket scienceEDS Systems
 
Event Driven with LibUV and ZeroMQ
Event Driven with LibUV and ZeroMQEvent Driven with LibUV and ZeroMQ
Event Driven with LibUV and ZeroMQLuke Luo
 
Tuga it 2017 - Event processing with Apache Storm
Tuga it 2017 - Event processing with Apache StormTuga it 2017 - Event processing with Apache Storm
Tuga it 2017 - Event processing with Apache StormNuno Caneco
 
LCA13: Common Clk Framework DVFS Roadmap
LCA13: Common Clk Framework DVFS RoadmapLCA13: Common Clk Framework DVFS Roadmap
LCA13: Common Clk Framework DVFS RoadmapLinaro
 
Bsdtw17: george neville neil: realities of dtrace on free-bsd
Bsdtw17: george neville neil: realities of dtrace on free-bsdBsdtw17: george neville neil: realities of dtrace on free-bsd
Bsdtw17: george neville neil: realities of dtrace on free-bsdScott Tsai
 
Iot with-the-best & VSCP
Iot with-the-best & VSCPIot with-the-best & VSCP
Iot with-the-best & VSCPAke Hedman
 
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept ExploitsSemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits星曼 陈
 

What's hot (20)

Mongodb meetup
Mongodb meetupMongodb meetup
Mongodb meetup
 
Transactional Memory
Transactional MemoryTransactional Memory
Transactional Memory
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Tools in action jdk mission control and flight recorder
Tools in action  jdk mission control and flight recorderTools in action  jdk mission control and flight recorder
Tools in action jdk mission control and flight recorder
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overview
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph Language
 
Observer pattern with Stl, boost and qt
Observer pattern with Stl, boost and qtObserver pattern with Stl, boost and qt
Observer pattern with Stl, boost and qt
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closures
 
RPC in Smalltalk
 RPC in Smalltalk RPC in Smalltalk
RPC in Smalltalk
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Omni ledger
Omni ledgerOmni ledger
Omni ledger
 
Logitoring - log-driven monitoring and the Rocket science
Logitoring - log-driven monitoring and the Rocket scienceLogitoring - log-driven monitoring and the Rocket science
Logitoring - log-driven monitoring and the Rocket science
 
jTransfo lightning talk
jTransfo lightning talkjTransfo lightning talk
jTransfo lightning talk
 
Event Driven with LibUV and ZeroMQ
Event Driven with LibUV and ZeroMQEvent Driven with LibUV and ZeroMQ
Event Driven with LibUV and ZeroMQ
 
Tuga it 2017 - Event processing with Apache Storm
Tuga it 2017 - Event processing with Apache StormTuga it 2017 - Event processing with Apache Storm
Tuga it 2017 - Event processing with Apache Storm
 
LCA13: Common Clk Framework DVFS Roadmap
LCA13: Common Clk Framework DVFS RoadmapLCA13: Common Clk Framework DVFS Roadmap
LCA13: Common Clk Framework DVFS Roadmap
 
Bsdtw17: george neville neil: realities of dtrace on free-bsd
Bsdtw17: george neville neil: realities of dtrace on free-bsdBsdtw17: george neville neil: realities of dtrace on free-bsd
Bsdtw17: george neville neil: realities of dtrace on free-bsd
 
Vft
VftVft
Vft
 
Iot with-the-best & VSCP
Iot with-the-best & VSCPIot with-the-best & VSCP
Iot with-the-best & VSCP
 
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept ExploitsSemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
 

Similar to Diagnosing HotSpot JVM Memory Leaks with JFR and JMC

JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance TuningJeremy Leisy
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoringSimon Ritter
 
Using FXML on Clojure
Using FXML on ClojureUsing FXML on Clojure
Using FXML on ClojureEunPyoung Kim
 
Software Profiling: Java Performance, Profiling and Flamegraphs
Software Profiling: Java Performance, Profiling and FlamegraphsSoftware Profiling: Java Performance, Profiling and Flamegraphs
Software Profiling: Java Performance, Profiling and FlamegraphsIsuru Perera
 
Python Generators
Python GeneratorsPython Generators
Python GeneratorsAkshar Raaj
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with MicronautQAware GmbH
 
Efficient Buffer Management
Efficient Buffer ManagementEfficient Buffer Management
Efficient Buffer Managementbasisspace
 
Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)RichardWarburton
 
Inside Android's UI / ABS 2013
Inside Android's UI / ABS 2013Inside Android's UI / ABS 2013
Inside Android's UI / ABS 2013Opersys inc.
 
Ext GWT - Overview and Implementation Case Study
Ext GWT - Overview and Implementation Case StudyExt GWT - Overview and Implementation Case Study
Ext GWT - Overview and Implementation Case StudyAvi Perez
 
Omp tutorial cpugpu_programming_cdac
Omp tutorial cpugpu_programming_cdacOmp tutorial cpugpu_programming_cdac
Omp tutorial cpugpu_programming_cdacGanesan Narayanasamy
 
Ob1k presentation at Java.IL
Ob1k presentation at Java.ILOb1k presentation at Java.IL
Ob1k presentation at Java.ILEran Harel
 
Log Event Stream Processing In Flink Way
Log Event Stream Processing In Flink WayLog Event Stream Processing In Flink Way
Log Event Stream Processing In Flink WayGeorge T. C. Lai
 

Similar to Diagnosing HotSpot JVM Memory Leaks with JFR and JMC (20)

JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance Tuning
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoring
 
Using FXML on Clojure
Using FXML on ClojureUsing FXML on Clojure
Using FXML on Clojure
 
Software Profiling: Java Performance, Profiling and Flamegraphs
Software Profiling: Java Performance, Profiling and FlamegraphsSoftware Profiling: Java Performance, Profiling and Flamegraphs
Software Profiling: Java Performance, Profiling and Flamegraphs
 
Java Profiling Future
Java Profiling FutureJava Profiling Future
Java Profiling Future
 
Python Generators
Python GeneratorsPython Generators
Python Generators
 
Java 2
Java 2Java 2
Java 2
 
Java under the hood
Java under the hoodJava under the hood
Java under the hood
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with Micronaut
 
Efficient Buffer Management
Efficient Buffer ManagementEfficient Buffer Management
Efficient Buffer Management
 
Unsafe Java
Unsafe JavaUnsafe Java
Unsafe Java
 
Java Memory Descreption
Java Memory DescreptionJava Memory Descreption
Java Memory Descreption
 
Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)
 
Java vs. C/C++
Java vs. C/C++Java vs. C/C++
Java vs. C/C++
 
Inside Android's UI / ABS 2013
Inside Android's UI / ABS 2013Inside Android's UI / ABS 2013
Inside Android's UI / ABS 2013
 
Ext GWT - Overview and Implementation Case Study
Ext GWT - Overview and Implementation Case StudyExt GWT - Overview and Implementation Case Study
Ext GWT - Overview and Implementation Case Study
 
Omp tutorial cpugpu_programming_cdac
Omp tutorial cpugpu_programming_cdacOmp tutorial cpugpu_programming_cdac
Omp tutorial cpugpu_programming_cdac
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
Ob1k presentation at Java.IL
Ob1k presentation at Java.ILOb1k presentation at Java.IL
Ob1k presentation at Java.IL
 
Log Event Stream Processing In Flink Way
Log Event Stream Processing In Flink WayLog Event Stream Processing In Flink Way
Log Event Stream Processing In Flink Way
 

Recently uploaded

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Recently uploaded (20)

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

Diagnosing HotSpot JVM Memory Leaks with JFR and JMC

  • 1. Diagnosing HotSpot JVM Memory Leaks with JFR and JMC Mushfekur Rahman Software Engineer II
  • 2. Today We’ll Talk About... ● Java Reference Types ● Understanding GC Reachability ● Memory Leak and java.lang.OutOfMemoryError ● Brief Introduction to JFR and JMC ● Few Classic Leak Scenarios
  • 3. Java Reference Types ● What about it? ○ How do we create a reference to an object? Car c = new Car(); ● This is not the only way we can create references *newsflash* ● Java offers four types of references 1. Strong 2. Soft 3. Weak 4. Phantom
  • 4. GC Reachability ● Let’s be a little hypothetical, what does GC do? ○ Simulate a finite memory space as infinite ● A common misunderstanding ○ GC collects unused/dead objects and reclaims memory space occupied by them ○ It’s actually the exact opposite ■ GC marks live objects ■ Reclaims everything else
  • 6. GC Reachability (contd.) ● Eligibility of an object to be GC’d depends on references ● GC algorithms traverse objects starting from GC root ○ GC roots ■ Source of Object trees ■ Possible candidates are active threads, and it's local variables, static variables and JNI references ○ All the objects that are reachable from GC root are marked as alive (not eligible for GC) ● If there’s no strong reference to an object, it’s going to be collected
  • 8. Behold The OutOfMemoryError ! ● It’s not that generic as you might’ve thought! ● Heap ○ Exception in thread "main": java.lang.OutOfMemoryError: Java heap space ○ This is what today’s session is mostly about ● PermGen ○ Exception in thread "main": java.lang.OutOfMemoryError: PermGen space ○ We’ll talk about PermGen leaks in another session ● Doesn’t always mean there’s a memory leak ○ Fragmentation ○ HotSpot VM throws OutOfMemoryError in case of excessive GC activities (e.g. 90% of execution time is being used for GC while 2% memory is being used)
  • 9. Wait a minute... ● So, we are fine as long as there’s no OutOfMemoryError? ○ Not really! ○ In fact, little unnoticed leaks are both decisive and vicious. ● What all these has to do with application performance? ○ GC is essential but expensive ○ GC is one of the biggest contributor to the overall latency in JVM applications ○ The less memory used, the less GC
  • 10. Java Mission Control ● Set of powerful monitoring and diagnosis tools that comes with Oracle JDK ● Two main parts ○ JMX Console ■ For monitoring JVM in real time ○ Java Flight Recorder ■ For collecting data about JVM (profiling) ● Can monitor JVM instances both local and remote ○ Event triggers ○ Execute troubleshooting commands on target JVM ● Supports plugins ○ For additional functionalities (e.g. heap dump analysis, DTrace recording etc.) ● Free for development use
  • 11. Java Flight Recorder ● Flight Recorder “A flight recorder, commonly known as a black box, although it is now orange-coloured, is an electronic recording device placed in an aircraft for the purpose of facilitating the investigation of aviation accidents and incidents.” - Wikipedia Fig. An actual aircraft Flight Recorder
  • 12. Java Flight Recorder (contd.) ● High performance event recorder ○ Built into the runtime ● Recordings are stored as binary chunks ○ Very detailed (records everything according to settings) ○ Self contained and self describing ● Very low overhead (<=1% according to Oracle) ○ Can keep it running always ○ Dumps can be taken from time to time using JVM debugging commands (e.g. jcmd)
  • 13. Java Flight Recorder (contd.) ● Recording Types ○ Continuous Recording ■ Have no end time ■ Must be explicitly dumped ○ Time Fixed Recordings (a.k.a Profiling Recordings) ■ Events will be captured within the specified timeframe ■ Will be automatically dumped in the specified location
  • 14. JFR Setup ● Start JVM with the following flags -XX:+UnlockCommercialFeatures -XX:+FlightRecorder ● For remote profiling add JMX related com.sun.management flags ● Additional parameters can be passed with -XX:StartFlightRecording ● Templates can be specified with a settings parameter ○ Templates can be created using JMC ○ Default template location $JAVA_HOME/jre/lib/jfr ○ Can only be used with JRockit or HotSpot (7u40 or later) ● *If there’s any* disable other profiling tool that does instrumentation (e.g. XRebel)
  • 15. Recording Events ● Default Recording ○ Starts a continuous recording ○ defaultrecording parameter is need to be added when starting JVM ○ dumponexit and dumponexitpath parameters can also be used with it ○ To get more info on what’s going on we can change log level -XX:FlightRecorderOptions=loglevel=trace ○ Example: The following will start a default recording - XX:FlightRecorderOptions=defaultrecording=true,dumponexit=true,dumponexi tpath=<path>
  • 16. Recording Events (contd.) ● Creating records on the fly ○ Need to pass signal in target JVM (using jcmd) ○ Available commands: JFR.start, JFR.check, JFR.stop, JFR.dump ○ Command format: jcmd <pid> <command> <parameters> ○ Starting a recording jcmd 4609 JFR.start name=DemoRecording settings=profile delay=20s duration=5m filename=/home/demorecording.jfr
  • 17. Back To Memory Leak!
  • 18. Common Pitfalls ● Non-static Inner Classes ○ Inner class has an implicit reference to the containing class ○ Isn’t supposed to live longer than the container class ○ What if an outer context holds a reference to the inner class? ■ Due to the implicit strong reference outer class cannot be GC’d public class OuterClass { /** * Outer class contents */ public class InnerClass { /** * Inner class contents */ } }
  • 19. Common Pitfalls (contd.) ● Flyweight Pattern ○ Structural design pattern aims to reduce cost of object creation ○ Reusing already existing objects by maintaining an object pool ○ Two states in every object ■ Intrinsic: Shareable values ■ Extrinsic: Non shareable values. Created and/or destroyed based on the client object actions.
  • 20. Common Pitfalls (contd.) ● JSP Tag Pooling ○ Servlet containers cache tag instances for performance reason ○ States goes back to the pool along with tag instances ○ Wait... it’s not just about heap leak ■ What if you have logic based on current state? ● Kaboom! ○ Should cleanup instance variable states after use ○ Example
  • 21. Common Pitfalls (contd.) ● Stateless Session Beans (Stateless EJBs) ○ Conversational state with a client is not stored ○ However, values of instance variables is held when returning in pool ○ Same as JSP Tag pooling it’s not just about memory ○ Should cleanup instance variable states, unless required
  • 22. Common Pitfalls (contd.) ● ThreadLocal instances ○ Lifecycle bound to the owning thread ○ Typical multithreaded services use thread pools ■ Threads gets re-used ○ What if you forget to cleanup after the thread finishes it’s work? ● Implicit leaks ○ Autoboxing in a loop ○ Serializing/cloning/copying complex object graphs
  • 23. Additional Resources ● Troubleshooting Guide for HotSpot VM (Chapter 3) ● Using Java Flight Recorder (JavaOne ‘15) ● Java Mission Control for Earthlings (Devoxx France ‘15) ● Running Java Flight Recorder