OnStackTest.java
public class OnStackTest {
public static void alloc() {
User u = new User();
u.id = 5;
u.name = "test";
}
public static void main(String[] args) throws InterruptedException {
long b = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
Thread.sleep(50);
alloc();
}
long e = System.currentTimeMillis();
System.out.println(e - b);
}
}
User.java
public class User {
public int id = 0;
public String name = "";
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
JVM flags
-server -Xmx10m -Xms10m -XX:+DoEscapeAnalysis -XX:+PrintGC -XX:-UseTLAB -XX:+EliminateAllocations
use jmap -histo
It is found that the user object has been created all the time on the heap. In theory, we should not replace the user object with scalar, and do not create the object on the heap?