今天早上我正在用 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/