String[] stringArray = new String[] { "abc", "xyz" };
执行此行有两个字符串文字在PERMGEN空间中创建“abc”和“xyz”。由于初始化有一个新的运算符,我不确定是否在HEAP上分配了任何内存。
谢谢你们。
答案 0 :(得分:1)
除了字符串文字之外的所有对象都是在堆上创建的。从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
答案 1 :(得分:0)
执行此操作时会发生以下情况:
即使实际的文字字符串保存在permgen的String池中,String- objects 仍然存储在堆中。