6. How to measure wasted memory?
Step 1: Capture Heap dumps in production*
https://blog.heaphero.io/2017/10/13/how-to-capture-java-heap-dumps-7-options/
Step 2: Analyze with HeapHero: https://heaphero.io
Reports amount of memory wasted, code triggering it, recommendations to fix.
* - if possible
9. 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'
10. 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
11. How intern() works?
“Hello World”
s1
s2
String pool
String s1 = new String("Hello World").intern();
String s2 = new String("Hello World").intern();
12. 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
13. Solution 3: Use String literals
public static final String HELLO_WORLD = “Hello World”;
14. Solution 4: Avoid creating strings
In DB store 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
…. 124
24. Yesterday’s key note: 2 instance variables/class
public class User {
private int field1;
private int field2;
private int field3;
:
private int field10;
}
public class User {
private Object1 obj1;
private Object2 obj2;
}
public class Object1 {
private int field1;
private Object3 obj3;
}
public class Object2 {
private int field2;
private Object4 obj4;
}
public class Object3 {
private int field3;
private Object5 obj5;
}
public class Object4 {
private int field4;
private Object6 obj6;
}52 bytes
i.e. 12 bytes header + (10 ints* 4 bytes) public class Object5 {
private int field5;
private Object6 obj7;
}
public class Object6 {
private int field6;
private Object3 obj8;
}
public class Object7 {
private int field7;
private Object4 obj9;
}
public class Object8 {
private int field8;
private int field9;
}
public class Object9 {
private int field10;
}
196 bytes (~4x more needed)
= 10 object headers * 12 + (10 ints * 4 bytes)
+ (9 object references * 4)