假设我们有256M的最大内存,为什么这段代码可以工作:
public static void main(String... args) {
for (int i = 0; i < 2; i++)
{
byte[] a1 = new byte[150000000];
}
byte[] a2 = new byte[150000000];
}
但是这一个抛出了一个OOME?
public static void main(String... args) {
//for (int i = 0; i < 2; i++)
{
byte[] a1 = new byte[150000000];
}
byte[] a2 = new byte[150000000];
}
发布于 2012-11-23 22:50:04
这是因为虽然a1
不在括号后面的作用域中,但在方法返回之前,它处于一种称为不可见的状态。
大多数现代JVM不会在变量a1
离开作用域时立即将其设置为null
(实际上,是否有内括号甚至不会更改生成的字节代码),因为它非常无效,而且通常无关紧要。因此,在方法返回之前,不能对a1
进行垃圾回收。
您可以通过添加以下行来检查这一点
a1 = null;
在括号内,这使得程序运行得很好。
隐形这个术语和解释取自这篇老论文:http://192.9.162.55/docs/books/performance/1st_edition/html/JPAppGC.fm.html
。
https://stackoverflow.com/questions/13531004
复制相似问题