理解栈溢出与堆溢出之二:Java堆内存空间不足引发的OutOfMemoryError
最编程
2024-02-12 13:07:15
...
堆中主要存放的是对象。
堆溢出:不断的new
对象会导致堆中空间溢出。如果虚拟机的栈内存允许动态扩展,当扩展栈容量无法申请到足够的内存时。
【示例】:
public class HeapError {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
try {
while (true) {
list.add("Floweryu");
}
} catch (Throwable e) {
System.out.println(list.size());
e.printStackTrace();
}
}
}
【输出】:
解决方法:调整堆的大小:Xmx
-Xmx size
Specifies the maximum size (in bytes) of the memory allocation pool in bytes. This value must be a multiple of 1024 and greater than 2 MB. Append the letter
k
orK
to indicate kilobytes,m
orM
to indicate megabytes, andg
orG
to indicate gigabytes. The default value is chosen at runtime based on system configuration. For server deployments,-Xms
and-Xmx
are often set to the same value. The following examples show how to set the maximum allowed size of allocated memory to 80 MB by using various units:-Xmx83886080
-Xmx81920k
-Xmx80mThe
-Xmx
option is equivalent to-XX:MaxHeapSize
.
设置-Xmx256M
后,输入如下,比之前小: