String[] stringArray = new String[] { "abc", "xyz" };
执行这一行,在 PERMGEN 空间中创建了两个字符串文字“abc”和“xyz”。由于初始化有一个新的运算符,我不确定 HEAP 上是否分配了任何内存。
多谢你们。
String[] stringArray = new String[] { "abc", "xyz" };
执行这一行,在 PERMGEN 空间中创建了两个字符串文字“abc”和“xyz”。由于初始化有一个新的运算符,我不确定 HEAP 上是否分配了任何内存。
多谢你们。
除字符串文字外,所有对象都是在堆上创建的。从 Java 7 开始,字符串文字也在堆上创建。
理论上,逃逸分析可以防止new
在堆上创建对象,并可能使用堆栈来代替。这在实践中很少发生 AFAIK。
在回答 EJP 问题时,我没有资助一个重要的例子,但是
来自http://www.oracle.com/technetwork/server-storage/ts-7392-159315.pdf第 22 页
New Technology: Escape Analysis
Definition: An object escapes the thread that allocated it if
some other thread can ever see it
If an object doesn't escape, we can abuse it
• Object explosion: allocate object's fields in different places
• Scalar replacement: store scalar fields in registers
• Thread stack allocation: store fields in stack frame
• Eliminate synchronization
• Eliminate initial object zero'ing
• Eliminate GC read / write barriers
Enabled with -XX:+DoEscapeAnalysis in JDKTM version 6
理论上这个特性已经存在了一段时间,但它并没有特别频繁地工作(即使找到一个人为的例子也很困难)在 Java 7 中,找到人为的例子更容易。;)
public class UsesWrappersMain {
public static void main(String... args) {
for (int j = 0; j < 10; j++) {
long used = used(), count = 0;
for (int i = 0; i < 2000; i++) {
count += printSum();
}
// add an object to show it is working
byte[] b = new byte[16];
long used2 = used();
System.out.printf("Memory used for %,d iterations was %,d bytes%n", count, used2 - used);
}
}
private static int printSum() {
int count = 0;
for (float i = 0; i < 10000; i++) {
// definitively not autoboxed.
Float j = new Float(i);
count++;
}
return count;
}
private static long used() {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
}
使用 -XX:-UseTLAB 运行时打印
Memory used for 20,000,000 iterations was 480,888 bytes
Memory used for 20,000,000 iterations was 32 bytes
Memory used for 20,000,000 iterations was 32 bytes
Memory used for 20,000,000 iterations was 32 bytes
Memory used for 20,000,000 iterations was 32 bytes
Memory used for 20,000,000 iterations was 32 bytes
Memory used for 20,000,000 iterations was 32 bytes
Memory used for 20,000,000 iterations was 0 bytes
Memory used for 20,000,000 iterations was 0 bytes
Memory used for 20,000,000 iterations was 0 bytes
如果您添加-XX:-DoEscapeAnalysis
的不是默认值
Memory used for 20,000,000 iterations was 320,000,928 bytes
Memory used for 20,000,000 iterations was 320,000,032 bytes
Memory used for 20,000,000 iterations was 320,000,032 bytes
Memory used for 20,000,000 iterations was 320,000,032 bytes
Memory used for 20,000,000 iterations was 320,000,032 bytes
Memory used for 20,000,000 iterations was 320,000,032 bytes
Memory used for 20,000,000 iterations was 320,000,032 bytes
Memory used for 20,000,000 iterations was 320,000,144 bytes
Memory used for 20,000,000 iterations was 320,000,032 bytes
Memory used for 20,000,000 iterations was 320,000,032 bytes
执行此操作时会发生什么,您将获得:
即使实际的文字字符串保存在 permgen 的字符串池中,String对象仍然存储在堆中。