jvm内存分为堆内存和栈内存这两块,堆内存用来存放对象等资源,栈内存用来存放线程和当前线程拥有的变量资源。
实验题目:堆内存调优
实验环境:
-Xms20m -Xmx20m 堆的最小值参数:-Xms20m 堆的最大值参数:-Xmx20m
实验步骤:
1.设置堆内存的最大值和最小值都为20m,编写堆内存溢出代码
import java.util.ArrayList; import java.util.List; ? public class HeapOutOfMemoryError { public static void main(String[] args) { List<HeapOutOfMemoryError> list = new ArrayList<>(); while(true){ list.add(new HeapOutOfMemoryError()); } } }
2.当控制台输出 Java heap space表示堆内存溢出,我们只需将堆内存设置得足够大即可
# 输出 Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:3210) at java.util.Arrays.copyOf(Arrays.java:3181) at java.util.ArrayList.grow(ArrayList.java:267) at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:241) at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:233) at java.util.ArrayList.add(ArrayList.java:464) at jvm.HeapOutOfMemoryError.main(HeapOutOfMemoryError.java:9)
实验题目:栈内存调优
实验环境:
-Xss2m
堆内存参数:-Xss2m
实验步骤:
1.设置堆内存参数为2m,编写栈内存溢出代码
public class JavaVMStackOverFlowError { private int stackLength = 1; public void stackLeak(){ stackLength++; stackLeak(); } public static void main(String[] args){ JavaVMStackOverFlowError sof = new JavaVMStackOverFlowError(); try{ sof.stackLeak(); }catch(Throwable e){ System.out.println("stackLength: "+sof.stackLength); throw e; } } }
2.当控制台输出 StackOverflowError表示栈内存溢出,我们只需将栈内存设置得足够大即可
# 输出 stackLength: 20701 Exception in thread "main" java.lang.StackOverflowError at jvm.JavaVMStackOverFlowError.stackLeak(JavaVMStackOverFlowError.java:7) at jvm.JavaVMStackOverFlowError.stackLeak(JavaVMStackOverFlowError.java:7) at jvm.JavaVMStackOverFlowError.stackLeak(JavaVMStackOverFlowError.java:7) at jvm.JavaVMStackOverFlowError.stackLeak(JavaVMStackOverFlowError.java:7) at jvm.JavaVMStackOverFlowError.stackLeak(JavaVMStackOverFlowError.java:7) at jvm.JavaVMStackOverFlowError.stackLeak(JavaVMStackOverFlowError.java:7) at jvm.JavaVMStackOverFlowError.stackLeak(JavaVMStackOverFlowError.java:7) at jvm.JavaVMStackOverFlowError.stackLeak(JavaVMStackOverFlowError.java:7) at jvm.JavaVMStackOverFlowError.stackLeak(JavaVMStackOverFlowError.java:7)
原文:https://www.cnblogs.com/XueTing/p/14963851.html