[英]Java constant pool removal at runtime
我有以下Java类:
public class Test {
public static void main(String[] args) {
if (false) {
log("String_to_be_never_printed_1");
}
if (isPrintable()) {
log("String_to_be_never_printed_2");
}
}
private static boolean isPrintable() {
return false;
}
private static void log(String s) {
System.out.println(s);
}
}
在两个if语句中,结果均为false。 当我输出此类的常量池表时,我得到:
Constant pool:
#1 = Class #2 // Test
#2 = Utf8 Test
....
#18 = Utf8 isPrintable
#19 = Utf8 ()Z
#20 = String #21 // String_to_be_never_printed_2
#21 = Utf8 String_to_be_never_printed_2
#22 = Methodref #1.#23 // Test.log:(Ljava/lang/String;)V
#23 = NameAndType #24:#25 // log:(Ljava/lang/String;)V
...
当无处可见String_to_be_never_printed_1时,存在String_to_be_never_printed_2(#20)。 这是预期的,因为编译器优化了第一个if语句。
我的问题是VM是否将设法从常量池中删除String_to_be_never_printed_2(因为将永远不会使用它)?
从常量池中什么都不会删除。 无论如何,这是没有目的的,因为删除不会影响实际的内存大小
JVM本身就有资格对堆内存中存在的对象进行垃圾回收。 常量池中的对象不是全部垃圾回收的,因为它们对分配给JVM的内存大小没有太大影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.