其他
Java中的对象都是在堆上分配的吗?
如果一个子程序分配一个对象并返回一个该对象的指针,该对象可能在程序中被访问到的地方无法确定——这样指针就成功“逃逸”了。如果指针存储在全局变量或者其它数据结构中,因为全局变量是可以在当前子程序之外访问的,此时指针也发生了逃逸。
static StringBuilder getStringBuilder1(String a, String b) {
StringBuilder builder = new StringBuilder(a);
builder.append(b);
return builder; // builder通过方法返回值逃逸到外部
}
static String getStringBuilder2(String a, String b) {
StringBuilder builder = new StringBuilder(a);
builder.append(b);
return builder.toString(); // builder范围维持在方法内部,未逃逸
}
public class EscapeAnalysisTest {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
for (int i = 0; i < 5000000; i++) {
allocate();
}
System.out.println((System.currentTimeMillis() - start) + " ms");
Thread.sleep(600000);
}
static void allocate() {
MyObject myObject = new MyObject(2019, 2019.0);
}
static class MyObject {
int a;
double b;
MyObject(int a, double b) {
this.a = a;
this.b = b;
}
}
}
~ java -XX:-DoEscapeAnalysis EscapeAnalysisTest
76 ms
~ jmap -histo 26031
num #instances #bytes class name
----------------------------------------------
1: 5000000 120000000 me.lmagics.EscapeAnalysisTest$MyObject
2: 636 12026792 [I
3: 3097 1524856 [B
4: 5088 759960 [C
5: 3067 73608 java.lang.String
6: 623 71016 java.lang.Class
7: 727 43248 [Ljava.lang.Object;
8: 532 17024 java.io.File
9: 225 14400 java.net.URL
10: 334 13360 java.lang.ref.Finalizer
# ......
开启逃逸分析
~ java -XX:+DoEscapeAnalysis EscapeAnalysisTest
4 ms
~ jmap -histo 26655
num #instances #bytes class name
----------------------------------------------
1: 592 11273384 [I
2: 90871 2180904 me.lmagics.EscapeAnalysisTest$MyObject
3: 3097 1524856 [B
4: 5088 759952 [C
5: 3067 73608 java.lang.String
6: 623 71016 java.lang.Class
7: 727 43248 [Ljava.lang.Object;
8: 532 17024 java.io.File
9: 225 14400 java.net.URL
10: 334 13360 java.lang.ref.Finalizer
# ......
static void allocate() {
int a = 2019;
double b = 2019.0;
}
private void someMethod() {
Object lockObject = new Object();
synchronized (lockObject) {
System.out.println(lockObject.hashCode());
}
}
private void someMethod() {
Object lockObject = new Object();
System.out.println(lockObject.hashCode());
}
END
学习资料:
最近热文:
Spring干货:
点击「阅读原文」带你飞~