java - 空循环比java中的非空循环消耗更多的内存

标签 java memory-management jvm

我正在阅读有关 Java 性能调优的文章并遇到了这个问题。

当我们运行时

public class test {
public static void main(String a[]){
    for(int i=0;i<1000000;i++){
        for(int j=0;j<100000;j++){
            Double d = new Double(1.0);
        }
    }
}
}

JVisualVM 显示了内存消耗图表:

enter image description here

但是当我们运行下面的代码时,

public class test {
public static void main(String a[]){
    for(int i=0;i<1000000;i++){
        for(int j=0;j<100000;j++){
        }
    }
}
}

JVisualVM 呈现锯齿波:

enter image description here

为什么会这样? 对于这两种情况,如何以及为什么更改 gc 触发限制?

最佳答案

关于你的 v1 for loops,你的局部变量,一旦它退出它的范围,它将被标记为 GC 可以自由收集,所以每隔一段时间 GC 就会启动并收集那段内存。

对于您的 v2 for 循环,那些空循环不会被编译器“优化掉”**,只有在多次调用之后,因为

JIT triggers AFTER a certain piece of code has been executed many times [1]

关于您的锯齿图案,ruakh对此有一个很好的解释 [2] :

If I'm not mistaken, part of the reason for this is that the monitor itself is forcing the application to create temporary objects that contain information about the state of garbage-collection and memory usage.

** 它们可能永远不会被删除,因为众所周知,这些空循环被用作等待机制。*

[1] Java: how much time does an empty loop use? - Simone Gianni's answer

[2] Why does an empty Java program consume memory?

关于java - 空循环比java中的非空循环消耗更多的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25402947/

相关文章:

arrays - 在 Matlab 中存储固定大小和数据类型的多个图像的所有可能且内存有效的方法是什么?

c++ - 坏指针和乱码数据

ruby - 如何改善 jRuby 加载时间?

java - JVM 堆栈大小规范

java - Android - 如何使用 okhttp-retrofit 从保存的缓存中使特定 URL 无效/删除?

java - Eclipse 的 Swing 设计器插件

java - 检测 GWT 中的离线和在线状态

JAVA 使用 InetAddress 指定端口

c - aligned_alloc返回赋值警告

java - 为什么大多数 JVM gc 不使用引用计数?