SlideShare a Scribd company logo
1 of 93
Download to read offline
A healthy diet
for your Java
application
Marharyta Nedzelska, @jMargaritaN
17.04.2024
Marharyta Nedzelska
Software Engineer @ Sonar
Conferences speaker & organizer
Java/Kotlin/Scala/...
Twitter: @jMargaritaN
https://www.freepik.com/vectors/ukraine-war
Ukraine war vector created by starline - www.freepik.com
Disclaimer
Disclaimer
How it all started?
Aleksey Shipilëv
Principal Engineer, Languages
and Runtimes, Amazon Web
Services
OpenJDK
JMH, JCStress, JOL
https://sonarcloud.io/project/overview?id=shipilev_jdk
I want to analyze Java & C++
code of OpenJDK in SonarCloud
…
using 3 Gb of RAM.
But I can’t :(
Aleksey Shipilëv
CI …
IDE
At the same time…
Am I making my
application “fit” too?
Is there any problem?
How to make your app “fit”?
Garbage Collector is not a wizard
I can’t collect objects that are
still referenced!
THE SYMPTOMS
Body
● Clothes too small
● Fat % too high
● Difficult to
run/walk/breathe
● BMI too high
● Always hungry
● Not satisfied with the
appearance…
● OutOfMemoryError
● More memory doesn’t help
● Much time on GC (GC
pauses)
● Spending too much CPU
● …
Application
Is there any problem?
How to make your app “fit”?
Let’s measure
Body
● Weight
● Fat & muscles
● BMI
● Heart rate
● Blood tests
● Eating habits
● …
● Memory usage
● Time
● CPU usage
● Heapdump
● Logs
● …
Application
Is there a leak?
Is there a leak?
Here are the heapdump, logs
and some memory analysis to
help you investigate…
Aleksey Shipilëv
java.lang.OutOfMemoryError: GC overhead limit exceeded
at com.google.protobuf.Utf8$UnsafeProcessor.decodeUtf8(na:2669)
at com.google.protobuf.Utf8.decodeUtf8(na:2905)
…
at com.sonar.A.D.A(na:648)
at com.sonar.A.D.B(na:2257)
at com.sonar.A.D.A(na:3069)
at com.sonar.cpp.F.readUcfg(na:2348)
java.lang.OutOfMemoryError: GC overhead limit exceeded
at com.google.protobuf.Utf8$UnsafeProcessor.decodeUtf8(na:2669)
at com.google.protobuf.Utf8.decodeUtf8(na:2905)
…
at com.sonar.A.D.A(na:648)
at com.sonar.A.D.B(na:2257)
at com.sonar.A.D.A(na:3069)
at com.sonar.cpp.F.readUcfg(na:2348)
java.lang.OutOfMemoryError: GC overhead limit exceeded
at com.google.protobuf.Utf8$UnsafeProcessor.decodeUtf8(na:2669)
at com.google.protobuf.Utf8.decodeUtf8(na:2905)
…
at com.sonar.A.D.A(na:648)
at com.sonar.A.D.B(na:2257)
at com.sonar.A.D.A(na:3069)
at com.sonar.cpp.F.readUcfg(na:2348)
Stacktrace is useless!!!
Is there any problem?
How to make your app “fit”?
Let’s measure
Let’s analyze
When static fields are eligible for garbage collection?
A) When the last instance is collected
B) When Class<.> instance is collected
C) When JVM exits
D) When class is unloaded
E) None of the above
32
When static fields are eligible for garbage collection?
A) When the last instance is collected
B) When Class<.> instance is collected
C) When JVM exits
D) When class is unloaded
E) None of the above
33
Instance Class Classloader
Static field
Instance Class Classloader
Static field
Instance Class Classloader
Static field
Instance Class Classloader
Static field
When static fields are eligible for garbage collection?
A) When the last instance is collected
B) When Class<.> instance is collected
C) When JVM exits
D) When class is unloaded
E) None of the above
F) When classloader is collected
38
Static is like sugar
● Static members live almost “forever”
● Static members should be avoided
● Static members shouldn’t be mutable
● Static members shouldn’t be updated from non-static methods
S2386
S2696
Is there any problem?
How to make your app “fit”?
Let’s measure
Let’s analyze
Find the root cause
equals() / hashCode() - carbs
● Should be used properly
● Always override equals() and hashCode() together
● Contract: if equals() returns true, hashCode() must be the same
● HashMap keys must be immutable
S1206
● https://jqno.nl/equalsverifier/
● https://github.com/jqno/equalsverifier
@Test
void test() {
EqualsVerifier
.forClass(FullName.class)
.verify();
}
Is there any problem?
How to make your app “fit”?
Let’s measure
Let’s analyze
Find the root cause
Fix it
Inner classes
● Should be static
● If still need it, take care of the lifecycle and outer class reference
S2694
ThreadLocals
● ThreadLocal lives as long as thread is alive
● Should be unset manually
S5164
Is there any problem?
How to make your app “fit”?
Let’s measure
Let’s analyze
Find the root cause
Fix it
Improve
Memory leaks Vs Memory footprint
Memory leak
A memory leak is an
unintentional form of
memory consumption
whereby the developer fails
to free an allocated block of
memory when no longer
needed.
- OWASP
Memory footprint
Memory footprint refers to
the amount of main
memory that a program
uses or references while
running.
- Wikipedia
Fixing memory leaks Reducing memory footprint
Reducing memory footprint
● Remove references manually
● Custom classloaders
try(var loader = new CustomClassloader(Example1.class.getClassLoader())) {
var clazz = loader.loadClass("com.example.classloader.MyExampleClass");
var instance = clazz.getConstructor().newInstance();
clazz.getMethod("doSomething").invoke(instance);
} catch (Exception e) {
throw new RuntimeException(e);
}
Reducing memory footprint
● Remove references manually
● Custom classloaders
● Minimize the living scope
Reducing memory footprint
● Remove references manually
● Custom classloaders
● Minimize the living scope
● Do all the necessary cleanup
Reducing memory footprint
● Remove references manually
● Custom classloaders
● Minimize the living scope
● Do all the necessary cleanup
● Use WeakReference
private WeakReference<BigObject> bigObject;
public void execute() {
var ref = bigObject.get();
if (ref == null) {
ref = recreateBigObject();
bigObject = new WeakReference<>(ref);
}
ref.hello();
}
Ballance is the key
● Losing too much
● Performance costs
● Need to find a balance
Is there any problem?
How to make your app “fit”?
Let’s measure
Let’s analyze
Find the root cause
Fix it
Improve
Fix it
Prevent
Remember how it all started?
I want to analyze Java & C++
code of OpenJDK in SonarCloud
…
using 3 Gb of RAM.
But I can’t :(
Aleksey Shipilëv
void run() {
var plugins = List.of(new JavaPlugin(), new CPPPlugin());
plugins.forEach(Plugin::execute);
}
MEMORY
What can we do?
● Make Java plugin last?
● Add some cleanup between plugins
● Reduce the life of Plugin
● Maybe Queue is better than List here
void run() {
ArrayDeque<Plugin> plugins = ...
for (var plugin = plugins.poll(); plugin != null;
plugin = plugins.poll()) {
plugin.execute();
}
}
● Follow a “healthy diet”
● Monitor memory usage
● GC logs
● Perform stress testing
● Use VisualVm, memory
analyzer,...
● Add tests
Java Object Layout (JOL)
https://github.com/openjdk/jol
@Test
public void myTest() {
var big = new BigObject().new SmallObject();
Assert.assertTrue(
GraphLayout.parseInstance(big).totalCount() < MAX_SIZE);
}
A healthy diet for your Java application
● Avoid statics and mutability
● Clean ThreadLocals
● Free resources
● Avoid Non-static inner classes
● If still need them, be careful
● Reduce the scope of references
● Monitor memory usage
How the story ended?
Useful links
● https://rules.sonarsource.com/
● https://owasp.org/www-community/vulnerabilities/Memory_leak
● https://www.baeldung.com/java-memory-leaks
● https://www.baeldung.com/java-static-fields-gc
● https://www.baeldung.com/java-weak-reference
Useful tools
● Visual VM : https://visualvm.github.io/
● Eclipse MAT : https://www.eclipse.org/mat/
● EqualsVerifier : https://jqno.nl/equalsverifier/
● Java Flight Recorder : https://docs.oracle.com/javacomponents/jmc-5-4/jfr-runtime-guide/about.htm#JFRUH173
● JOL : https://github.com/openjdk/jol
● Sonar : https://www.sonarsource.com/products/sonarqube/
Some kudos
Evgeny Mandrikov
Some kudos
JVM squad
Thanks for your
attention!
Questions?

More Related Content

Similar to A healthy diet for your Java application Devoxx France.pdf

Presentations Unusual Java Bugs And Detecting Them Using Foss Tools
Presentations Unusual Java Bugs And Detecting Them Using Foss ToolsPresentations Unusual Java Bugs And Detecting Them Using Foss Tools
Presentations Unusual Java Bugs And Detecting Them Using Foss Tools
Ganesh Samarthyam
 
Eclipse Demo Camp Bangalore 2009 - JSDT
Eclipse Demo Camp Bangalore 2009 - JSDTEclipse Demo Camp Bangalore 2009 - JSDT
Eclipse Demo Camp Bangalore 2009 - JSDT
deepakazad
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
Anton Arhipov
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
DjangoCon2008
 

Similar to A healthy diet for your Java application Devoxx France.pdf (20)

Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
 
Determinism in finance
Determinism in financeDeterminism in finance
Determinism in finance
 
Scala's evolving ecosystem- Introduction to Scala.js
Scala's evolving ecosystem- Introduction to Scala.jsScala's evolving ecosystem- Introduction to Scala.js
Scala's evolving ecosystem- Introduction to Scala.js
 
SpringOne Platform recap 정윤진
SpringOne Platform recap 정윤진SpringOne Platform recap 정윤진
SpringOne Platform recap 정윤진
 
Power Up Your Build - Omer van Kloeten @ Wix 2018-04
Power Up Your Build - Omer van Kloeten @ Wix 2018-04Power Up Your Build - Omer van Kloeten @ Wix 2018-04
Power Up Your Build - Omer van Kloeten @ Wix 2018-04
 
Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.
Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.
Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.
 
Unit testing hippo
Unit testing hippoUnit testing hippo
Unit testing hippo
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone Civetta
 
Presentations Unusual Java Bugs And Detecting Them Using Foss Tools
Presentations Unusual Java Bugs And Detecting Them Using Foss ToolsPresentations Unusual Java Bugs And Detecting Them Using Foss Tools
Presentations Unusual Java Bugs And Detecting Them Using Foss Tools
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript
 
Unsafe Java
Unsafe JavaUnsafe Java
Unsafe Java
 
Troubleshooting Java HotSpot VM
Troubleshooting Java HotSpot VMTroubleshooting Java HotSpot VM
Troubleshooting Java HotSpot VM
 
Eclipse Demo Camp Bangalore 2009 - JSDT
Eclipse Demo Camp Bangalore 2009 - JSDTEclipse Demo Camp Bangalore 2009 - JSDT
Eclipse Demo Camp Bangalore 2009 - JSDT
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
 
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
 
Js tacktalk team dev js testing performance
Js tacktalk team dev js testing performanceJs tacktalk team dev js testing performance
Js tacktalk team dev js testing performance
 
Elastic JVM for Scalable Java EE Applications Running in Containers #Jakart...
Elastic JVM  for Scalable Java EE Applications  Running in Containers #Jakart...Elastic JVM  for Scalable Java EE Applications  Running in Containers #Jakart...
Elastic JVM for Scalable Java EE Applications Running in Containers #Jakart...
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
 

Recently uploaded

Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Lisi Hocke
 
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
drm1699
 

Recently uploaded (20)

Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
 
Effective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConEffective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeCon
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdf
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
 
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
 
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
 
The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test Automation
 
Test Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdfTest Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdf
 
BusinessGPT - Security and Governance for Generative AI
BusinessGPT  - Security and Governance for Generative AIBusinessGPT  - Security and Governance for Generative AI
BusinessGPT - Security and Governance for Generative AI
 
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
 
A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdf
 
Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?
 
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
 
Rapidoform for Modern Form Building and Insights
Rapidoform for Modern Form Building and InsightsRapidoform for Modern Form Building and Insights
Rapidoform for Modern Form Building and Insights
 
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale IbridaUNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
 
Spring into AI presented by Dan Vega 5/14
Spring into AI presented by Dan Vega 5/14Spring into AI presented by Dan Vega 5/14
Spring into AI presented by Dan Vega 5/14
 
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
Auto Affiliate  AI Earns First Commission in 3 Hours..pdfAuto Affiliate  AI Earns First Commission in 3 Hours..pdf
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
 
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
 
Novo Nordisk: When Knowledge Graphs meet LLMs
Novo Nordisk: When Knowledge Graphs meet LLMsNovo Nordisk: When Knowledge Graphs meet LLMs
Novo Nordisk: When Knowledge Graphs meet LLMs
 

A healthy diet for your Java application Devoxx France.pdf