SlideShare a Scribd company logo
How (and why)
to write memory-efficient code?
JAX Online 2020 conference
Ram Lakshmanan
Architect: GCeasy.io, fastThread.io, HeapHero.io
https://tinyurl.com/y3q5j5oj
Case Study 1: Memory wasted by major travel app
https://dzone.com/articles/memory-wasted-by-spring-boot-application
Case Study 2: Memory wasted by Spring Boot
Do I need to care about memory?
It’s very cheap!
1970s
1 Byte = 1 $
2019
FRACTION OF COST
My case: Memory is not cheap!
Memory gets saturated first.
Other resources are partially or under
utilized.
3. Storage
4. Network
1. CPU
2. Memory
Memory wasted by my application
1: Capture Heap dumps in production*
https://blog.heaphero.io/2017/10/13/how-to-capture-java-heap-dumps-7-options/
2: Analyze with HeapHero: https://heaphero.io
Reports amount of memory wasted, code triggering it, recommendations to fix.
* - if possible
How to find it?
Inefficient Collections
How collections work?
List<User> users = new ArrayList<>();
users.add(user);
2 54 6 7 8 1093
wasted
11
ArrayList underlyingly maintains
Object[]
initial capacity = 10
How collections work?
1 2 54 6 7 8 1093
wasted
List<User> users = new ArrayList<>();
for (int counter = 1; counter <= 11; ++counter) {
users.add(user);
}
1 2 54 6 7 8 1093 11 12 1514 17 18 201913 16
1 2 54 6 7 8 93 11 12 1514 17 18 201913 16 21 22 2524 26 27 28 2923 31 32 3534 37 38 403933 3630
wasted
10
for (int counter = 1; counter <= 21; ++counter) {
users.add(user);
}
Solution 1: Use capacity
new ArrayList<>(3);
new ArrayList<>();
Solution 2: Lazy initialization
private List<User> users = new ArrayList<>();
public void addUser(User user) {
users.add(user);
}
private List<User> users;
public void addUser(User user) {
if (users == null) {
users = new ArrayList<>(5);
}
users.add(user);
}
Solution 3: avoid clear()
List<User> users = new ArrayList<>();
users = null;
List<User> users = new ArrayList<>();
users.clear();
Duplicate Strings
What is duplicate String?
String s1 = new String("Hello World");
String s2 = new String("Hello World");
System.out.println(s1.equals(s2)); // prints 'true'
System.out.println((s1 == s2)); // prints 'false'
Solution 1: intern()
String s1 = new String("Hello World").intern();
String s2 = new String("Hello World").intern();
System.out.println(s1.equals(s2)); // prints 'true'
System.out.println((s1 == s2)); // prints 'true'
>>> s1 = intern(’Hello World')
Java
Python
How intern() works?
“Hello World”
s1
s2
String pool
String s1 = new String("Hello World").intern();
String s2 = new String("Hello World").intern();
Solution 2: UseStringDeduplication
• -XX:+UseStringDeduplication
• Works only with
 G1 GC algorithm
 Java 8 update 20
• Real life case study:
 https://blog.gceasy.io/2018/07/17/disappointing-story-on-memory-optimization/
 Long lived objects (-XX:StringDeduplicationAgeThreshold=3)
• Check GC pause time impact
Solution 3: Use String Literals
public static final String MY_STRING = “Hello World”;
Solution 4: Avoid creating strings
a. Use enum
b. In DB, consider storing data as primitive types!
user
id
Name …. country
1 Joe Libson …. Canada
2 Nathan Ray …. Canada
3 Chris Mang …. USA
4 Erik Pilz …. USA
5 Lakshmi
Singh
…. India
user
id
Name …. country
1 Joe Libson …. 2
2 Nathan Ray …. 2
3 Chris Mang …. 1
4 Erik Pilz …. 1
5 Lakshmi
Singh
…. 145
Object Overhead
public class User {
private String name;
private int age;
private float weight;
}
new User();
Object Header
name
age
weight
12 bytes
4 bytes
4 bytes
4 bytes
Fixed overhead
1. Virtual method invocation
2. ‘synchronized’ object lock
3. Garbage collection
4. Object book keeping
24 bytes
Object overhead
Boxed numbers: java.lang.Integer
• int: 4 bytes
• java.lang.Integer: 16 bytes
Data is 4 bytes, object overhead is 12 bytes
Object Header
int
12 bytes
4 bytes
16 bytes
How all memory is wasted?
1. Duplicate Strings: https://heaphero.io/heap-recommendations/duplicate-strings.html
2. Wrong memory size settings
3. Inefficient Collections: http://heaphero.io/heap-recommendations/inefficient-collections.html
4. Duplicate Objects: https://heaphero.io/heap-recommendations/duplicate-objects.html
5. Duplicate arrays: https://heaphero.io/heap-recommendations/duplicate-primitive-arrays.html
6. Inefficient arrays: https://heaphero.io/heap-recommendations/inefficient-primitive-arrays.html
7. Objects waiting for finalization: https://heaphero.io/heap-recommendations/objects-
waiting-finalization.html
8. Boxed numbers: https://heaphero.io/heap-recommendations/boxed-numbers.html
9. Object Headers: https://heaphero.io/heap-recommendations/object-headers.html
File Descriptors
File descriptor is a handle to access: File, Pipe,
Network Connections. If count grows it’s a lead
indicator that application isn’t closing resources
properly.
Few more…
TCP/IP States, Hosts count, IOPS, ..
Thread States
If BLOCKED thread state count grows, it’s
an early indication that your application has
potential to become unresponsive
GC Throughput
Amount time application spends in processing
customer transactions vs amount of time application
spend in doing GC
Avg allocation rate
Amount of objects created in a unit of
time
GC Latency
If pause time starts to increase, then
it’s an indication that app is suffering
from memory problems
Micrometrics
https://blog.gceasy.io/2019/03/13/micrometrics-to-forecast-application-performance/
CI/CD – catch early in the game
Integrate micrometrics into CI/CD pipeline
Avg allocation rate
https://blog.gceasy.io/2016/06/18/garbage-collection-log-analysis-api/
Memory wasted metrics
https://blog.heaphero.io/2018/06/22/heap-dump-analysis-api/
Benefits: Optimizing Memory
Save millions, billions of $ in computing cost
Delight customer:
• Better Response time
• Garbage collection pause time drops
Fascinating to read
Thank You my Friends!
Ram Lakshmanan
ram@tier1app.com
@tier1app
linkedin.com/company/gceasy
This deck will be published in: https://blog.heaphero.io

More Related Content

What's hot

Accelerating Incident Response To Production Outages
Accelerating Incident Response To Production OutagesAccelerating Incident Response To Production Outages
Accelerating Incident Response To Production Outages
Tier1 app
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
Andrei Pangin
 
Find bottleneck and tuning in Java Application
Find bottleneck and tuning in Java ApplicationFind bottleneck and tuning in Java Application
Find bottleneck and tuning in Java Application
guest1f2740
 
marko_go_in_badoo
marko_go_in_badoomarko_go_in_badoo
marko_go_in_badoo
Marko Kevac
 
Thread dump troubleshooting
Thread dump troubleshootingThread dump troubleshooting
Thread dump troubleshooting
Jerry Chan
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
Andrei Pangin
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?
Andrei Pangin
 
So You Want To Write Your Own Benchmark
So You Want To Write Your Own BenchmarkSo You Want To Write Your Own Benchmark
So You Want To Write Your Own Benchmark
Dror Bereznitsky
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
Andrei Pangin
 
Java Heap Dump Analysis Primer
Java Heap Dump Analysis PrimerJava Heap Dump Analysis Primer
Java Heap Dump Analysis Primer
Kyle Hodgson
 
jvm goes to big data
jvm goes to big datajvm goes to big data
jvm goes to big data
srisatish ambati
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
The origin: Init (compact version)
The origin: Init (compact version)The origin: Init (compact version)
The origin: Init (compact version)
Tzung-Bi Shih
 
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
Tzung-Bi Shih
 
Jdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsJdk Tools For Performance Diagnostics
Jdk Tools For Performance Diagnostics
Dror Bereznitsky
 
JDK not so hidden treasures
JDK not so hidden treasuresJDK not so hidden treasures
JDK not so hidden treasures
Andrzej Grzesik
 
Refactoring for testability c++
Refactoring for testability c++Refactoring for testability c++
Refactoring for testability c++
Dimitrios Platis
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
Zone IDA Proc
Zone IDA ProcZone IDA Proc
Zone IDA Proc
Tzung-Bi Shih
 
Gc crash course (1)
Gc crash course (1)Gc crash course (1)
Gc crash course (1)
Tier1 app
 

What's hot (20)

Accelerating Incident Response To Production Outages
Accelerating Incident Response To Production OutagesAccelerating Incident Response To Production Outages
Accelerating Incident Response To Production Outages
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
 
Find bottleneck and tuning in Java Application
Find bottleneck and tuning in Java ApplicationFind bottleneck and tuning in Java Application
Find bottleneck and tuning in Java Application
 
marko_go_in_badoo
marko_go_in_badoomarko_go_in_badoo
marko_go_in_badoo
 
Thread dump troubleshooting
Thread dump troubleshootingThread dump troubleshooting
Thread dump troubleshooting
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?
 
So You Want To Write Your Own Benchmark
So You Want To Write Your Own BenchmarkSo You Want To Write Your Own Benchmark
So You Want To Write Your Own Benchmark
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
 
Java Heap Dump Analysis Primer
Java Heap Dump Analysis PrimerJava Heap Dump Analysis Primer
Java Heap Dump Analysis Primer
 
jvm goes to big data
jvm goes to big datajvm goes to big data
jvm goes to big data
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
The origin: Init (compact version)
The origin: Init (compact version)The origin: Init (compact version)
The origin: Init (compact version)
 
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
 
Jdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsJdk Tools For Performance Diagnostics
Jdk Tools For Performance Diagnostics
 
JDK not so hidden treasures
JDK not so hidden treasuresJDK not so hidden treasures
JDK not so hidden treasures
 
Refactoring for testability c++
Refactoring for testability c++Refactoring for testability c++
Refactoring for testability c++
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Zone IDA Proc
Zone IDA ProcZone IDA Proc
Zone IDA Proc
 
Gc crash course (1)
Gc crash course (1)Gc crash course (1)
Gc crash course (1)
 

Similar to How & why-memory-efficient?

Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and Tuning
Carol McDonald
 
CodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory laneCodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory lane
Maarten Balliauw
 
Matthew Vignau: Memory Management in SharePoint 2007 Development
Matthew Vignau: Memory Management in SharePoint 2007 DevelopmentMatthew Vignau: Memory Management in SharePoint 2007 Development
Matthew Vignau: Memory Management in SharePoint 2007 Development
SharePoint Saturday NY
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinar
Maarten Balliauw
 
6tips web-perf
6tips web-perf6tips web-perf
6tips web-perf
Luciano Mammino
 
computer notes - Data Structures - 1
computer notes - Data Structures - 1computer notes - Data Structures - 1
computer notes - Data Structures - 1
ecomputernotes
 
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management....NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
NETFest
 
Computer notes - data structures
Computer notes - data structuresComputer notes - data structures
Computer notes - data structures
ecomputernotes
 
Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)
Maarten Balliauw
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
Maarten Balliauw
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
sekar c
 
Mobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneMobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, Pune
Bhuvan Khanna
 
Talking trash
Talking trashTalking trash
Talking trash
michael.labriola
 
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
Shaul Rosenzwieg
 
Dealing with web scale data
Dealing with web scale dataDealing with web scale data
Dealing with web scale data
Jnaapti
 
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
Maarten Balliauw
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
02D-Memory Management in Java.pptx
02D-Memory Management in Java.pptx02D-Memory Management in Java.pptx
02D-Memory Management in Java.pptx
AnhNhatNguyen5
 
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
Maarten Balliauw
 
Goroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in GoGoroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in Go
Yu-Shuan Hsieh
 

Similar to How & why-memory-efficient? (20)

Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and Tuning
 
CodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory laneCodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory lane
 
Matthew Vignau: Memory Management in SharePoint 2007 Development
Matthew Vignau: Memory Management in SharePoint 2007 DevelopmentMatthew Vignau: Memory Management in SharePoint 2007 Development
Matthew Vignau: Memory Management in SharePoint 2007 Development
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinar
 
6tips web-perf
6tips web-perf6tips web-perf
6tips web-perf
 
computer notes - Data Structures - 1
computer notes - Data Structures - 1computer notes - Data Structures - 1
computer notes - Data Structures - 1
 
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management....NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
 
Computer notes - data structures
Computer notes - data structuresComputer notes - data structures
Computer notes - data structures
 
Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
 
Mobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneMobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, Pune
 
Talking trash
Talking trashTalking trash
Talking trash
 
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
 
Dealing with web scale data
Dealing with web scale dataDealing with web scale data
Dealing with web scale data
 
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
02D-Memory Management in Java.pptx
02D-Memory Management in Java.pptx02D-Memory Management in Java.pptx
02D-Memory Management in Java.pptx
 
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
 
Goroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in GoGoroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in Go
 

More from Tier1 app

DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Top-5-java-perf-problems-jax_mainz_2024.pptx
Top-5-java-perf-problems-jax_mainz_2024.pptxTop-5-java-perf-problems-jax_mainz_2024.pptx
Top-5-java-perf-problems-jax_mainz_2024.pptx
Tier1 app
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
Tier1 app
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Top-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptxTop-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptx
Tier1 app
 
predicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptxpredicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptx
Tier1 app
 
Top-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptx
Tier1 app
 
predicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
Tier1 app
 
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
Tier1 app
 
7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx
Tier1 app
 
Top-5-Performance-JaxLondon-2023.pptx
Top-5-Performance-JaxLondon-2023.pptxTop-5-Performance-JaxLondon-2023.pptx
Top-5-Performance-JaxLondon-2023.pptx
Tier1 app
 
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
Tier1 app
 
MAJOR OUTAGES IN MAJOR ENTERPRISES
MAJOR OUTAGES IN MAJOR ENTERPRISESMAJOR OUTAGES IN MAJOR ENTERPRISES
MAJOR OUTAGES IN MAJOR ENTERPRISES
Tier1 app
 
KnowAPIs-UnknownPerf-confoo-2023 (1).pptx
KnowAPIs-UnknownPerf-confoo-2023 (1).pptxKnowAPIs-UnknownPerf-confoo-2023 (1).pptx
KnowAPIs-UnknownPerf-confoo-2023 (1).pptx
Tier1 app
 
memory-patterns-confoo-2023.pptx
memory-patterns-confoo-2023.pptxmemory-patterns-confoo-2023.pptx
memory-patterns-confoo-2023.pptx
Tier1 app
 
this-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptxthis-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptx
Tier1 app
 
millions-gc-jax-2022.pptx
millions-gc-jax-2022.pptxmillions-gc-jax-2022.pptx
millions-gc-jax-2022.pptx
Tier1 app
 
lets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptxlets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptx
Tier1 app
 
‘16 artifacts’ to capture when there is a production problem
‘16 artifacts’ to capture when there is a production problem‘16 artifacts’ to capture when there is a production problem
‘16 artifacts’ to capture when there is a production problem
Tier1 app
 

More from Tier1 app (20)

DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Top-5-java-perf-problems-jax_mainz_2024.pptx
Top-5-java-perf-problems-jax_mainz_2024.pptxTop-5-java-perf-problems-jax_mainz_2024.pptx
Top-5-java-perf-problems-jax_mainz_2024.pptx
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Top-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptxTop-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptx
 
predicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptxpredicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptx
 
Top-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptx
 
predicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
 
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
 
7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx
 
Top-5-Performance-JaxLondon-2023.pptx
Top-5-Performance-JaxLondon-2023.pptxTop-5-Performance-JaxLondon-2023.pptx
Top-5-Performance-JaxLondon-2023.pptx
 
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
 
MAJOR OUTAGES IN MAJOR ENTERPRISES
MAJOR OUTAGES IN MAJOR ENTERPRISESMAJOR OUTAGES IN MAJOR ENTERPRISES
MAJOR OUTAGES IN MAJOR ENTERPRISES
 
KnowAPIs-UnknownPerf-confoo-2023 (1).pptx
KnowAPIs-UnknownPerf-confoo-2023 (1).pptxKnowAPIs-UnknownPerf-confoo-2023 (1).pptx
KnowAPIs-UnknownPerf-confoo-2023 (1).pptx
 
memory-patterns-confoo-2023.pptx
memory-patterns-confoo-2023.pptxmemory-patterns-confoo-2023.pptx
memory-patterns-confoo-2023.pptx
 
this-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptxthis-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptx
 
millions-gc-jax-2022.pptx
millions-gc-jax-2022.pptxmillions-gc-jax-2022.pptx
millions-gc-jax-2022.pptx
 
lets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptxlets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptx
 
‘16 artifacts’ to capture when there is a production problem
‘16 artifacts’ to capture when there is a production problem‘16 artifacts’ to capture when there is a production problem
‘16 artifacts’ to capture when there is a production problem
 

Recently uploaded

8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
Rakesh Kumar R
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
NishanthaBulumulla1
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
Karya Keeper
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 

Recently uploaded (20)

8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 

How & why-memory-efficient?

  • 1. How (and why) to write memory-efficient code? JAX Online 2020 conference Ram Lakshmanan Architect: GCeasy.io, fastThread.io, HeapHero.io
  • 2. https://tinyurl.com/y3q5j5oj Case Study 1: Memory wasted by major travel app
  • 4. Do I need to care about memory? It’s very cheap! 1970s 1 Byte = 1 $ 2019 FRACTION OF COST
  • 5. My case: Memory is not cheap! Memory gets saturated first. Other resources are partially or under utilized. 3. Storage 4. Network 1. CPU 2. Memory
  • 6. Memory wasted by my application 1: Capture Heap dumps in production* https://blog.heaphero.io/2017/10/13/how-to-capture-java-heap-dumps-7-options/ 2: Analyze with HeapHero: https://heaphero.io Reports amount of memory wasted, code triggering it, recommendations to fix. * - if possible How to find it?
  • 8. How collections work? List<User> users = new ArrayList<>(); users.add(user); 2 54 6 7 8 1093 wasted 11 ArrayList underlyingly maintains Object[] initial capacity = 10
  • 9. How collections work? 1 2 54 6 7 8 1093 wasted List<User> users = new ArrayList<>(); for (int counter = 1; counter <= 11; ++counter) { users.add(user); } 1 2 54 6 7 8 1093 11 12 1514 17 18 201913 16 1 2 54 6 7 8 93 11 12 1514 17 18 201913 16 21 22 2524 26 27 28 2923 31 32 3534 37 38 403933 3630 wasted 10 for (int counter = 1; counter <= 21; ++counter) { users.add(user); }
  • 10. Solution 1: Use capacity new ArrayList<>(3); new ArrayList<>();
  • 11. Solution 2: Lazy initialization private List<User> users = new ArrayList<>(); public void addUser(User user) { users.add(user); } private List<User> users; public void addUser(User user) { if (users == null) { users = new ArrayList<>(5); } users.add(user); }
  • 12. Solution 3: avoid clear() List<User> users = new ArrayList<>(); users = null; List<User> users = new ArrayList<>(); users.clear();
  • 14. What is duplicate String? String s1 = new String("Hello World"); String s2 = new String("Hello World"); System.out.println(s1.equals(s2)); // prints 'true' System.out.println((s1 == s2)); // prints 'false'
  • 15. Solution 1: intern() String s1 = new String("Hello World").intern(); String s2 = new String("Hello World").intern(); System.out.println(s1.equals(s2)); // prints 'true' System.out.println((s1 == s2)); // prints 'true' >>> s1 = intern(’Hello World') Java Python
  • 16. How intern() works? “Hello World” s1 s2 String pool String s1 = new String("Hello World").intern(); String s2 = new String("Hello World").intern();
  • 17. Solution 2: UseStringDeduplication • -XX:+UseStringDeduplication • Works only with  G1 GC algorithm  Java 8 update 20 • Real life case study:  https://blog.gceasy.io/2018/07/17/disappointing-story-on-memory-optimization/  Long lived objects (-XX:StringDeduplicationAgeThreshold=3) • Check GC pause time impact
  • 18. Solution 3: Use String Literals public static final String MY_STRING = “Hello World”;
  • 19. Solution 4: Avoid creating strings a. Use enum b. In DB, consider storing data as primitive types! user id Name …. country 1 Joe Libson …. Canada 2 Nathan Ray …. Canada 3 Chris Mang …. USA 4 Erik Pilz …. USA 5 Lakshmi Singh …. India user id Name …. country 1 Joe Libson …. 2 2 Nathan Ray …. 2 3 Chris Mang …. 1 4 Erik Pilz …. 1 5 Lakshmi Singh …. 145
  • 21. public class User { private String name; private int age; private float weight; } new User(); Object Header name age weight 12 bytes 4 bytes 4 bytes 4 bytes Fixed overhead 1. Virtual method invocation 2. ‘synchronized’ object lock 3. Garbage collection 4. Object book keeping 24 bytes Object overhead
  • 22. Boxed numbers: java.lang.Integer • int: 4 bytes • java.lang.Integer: 16 bytes Data is 4 bytes, object overhead is 12 bytes Object Header int 12 bytes 4 bytes 16 bytes
  • 23. How all memory is wasted? 1. Duplicate Strings: https://heaphero.io/heap-recommendations/duplicate-strings.html 2. Wrong memory size settings 3. Inefficient Collections: http://heaphero.io/heap-recommendations/inefficient-collections.html 4. Duplicate Objects: https://heaphero.io/heap-recommendations/duplicate-objects.html 5. Duplicate arrays: https://heaphero.io/heap-recommendations/duplicate-primitive-arrays.html 6. Inefficient arrays: https://heaphero.io/heap-recommendations/inefficient-primitive-arrays.html 7. Objects waiting for finalization: https://heaphero.io/heap-recommendations/objects- waiting-finalization.html 8. Boxed numbers: https://heaphero.io/heap-recommendations/boxed-numbers.html 9. Object Headers: https://heaphero.io/heap-recommendations/object-headers.html
  • 24. File Descriptors File descriptor is a handle to access: File, Pipe, Network Connections. If count grows it’s a lead indicator that application isn’t closing resources properly. Few more… TCP/IP States, Hosts count, IOPS, .. Thread States If BLOCKED thread state count grows, it’s an early indication that your application has potential to become unresponsive GC Throughput Amount time application spends in processing customer transactions vs amount of time application spend in doing GC Avg allocation rate Amount of objects created in a unit of time GC Latency If pause time starts to increase, then it’s an indication that app is suffering from memory problems Micrometrics https://blog.gceasy.io/2019/03/13/micrometrics-to-forecast-application-performance/
  • 25. CI/CD – catch early in the game Integrate micrometrics into CI/CD pipeline Avg allocation rate https://blog.gceasy.io/2016/06/18/garbage-collection-log-analysis-api/ Memory wasted metrics https://blog.heaphero.io/2018/06/22/heap-dump-analysis-api/
  • 26. Benefits: Optimizing Memory Save millions, billions of $ in computing cost Delight customer: • Better Response time • Garbage collection pause time drops
  • 28. Thank You my Friends! Ram Lakshmanan ram@tier1app.com @tier1app linkedin.com/company/gceasy This deck will be published in: https://blog.heaphero.io