Java 使用的内存多于分配的内存

标签 java multithreading memory synchronization stack-overflow

今天早上我正在用 Java 测试一些东西,我运行了这段代码,预计会出现 OutOfMemoryError:

public class SynchronizedSpammer {
    public static void main(String[] args) {
        while (true) {
            new Thread(new Runnable() {
                public void run() {
                    syncWait();
                }
            }).start();
        }
    }

    public static synchronized void syncWait() {
        try {
            Thread.sleep(100000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

令我惊讶的是,我的计算机在用完所有内存和交换区后几秒钟就崩溃了。

这也有效:

public class Crash {
    public static void main(String[] args) {
        while (true) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(10000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}

发生了什么事?为什么内存不受 Xmx 限制?

最佳答案

您创建了太多Thread对象!

while (true) {
   new Thread(new Runnable() {
        public void run() {
            syncWait();
        }
    }).start();
}

你是这个意思吗?

new Thread(new Runnable() {
    public void run() {
        while (true) {
            syncWait();
        }
    }
}).start();

关于Java 使用的内存多于分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22395286/

相关文章:

java - JMS session 线程影响

C++ 任务链

python - 是什么导致我的 Python 程序使用 opencv 耗尽内存?

java - 无法使用 javascript 隐藏 <td> 标记,并且无法将 servlet 编写为 <td tag> 的 id

java - Tomcat 中的线程复用

java - 通过 Jar 文件实现事件发布功能

java - HTTP post 请求返回 HTML 代码而不是 JSON 数据

java - 在队列中等待的线程,Java

c - 无需外部工具即可获取系统总内存

iOS 应用程序内存不足处理