常量池存在于方法区中,方法区:
1.又叫静态区,跟堆一样,被所有的线程共享。方法区包含所有的class和static变量。
2.方法区中包含的都是在整个程序中永远唯一的元素,如class,static变量。
根据以上两点,我们模拟方法区内存溢出可以一直往方法区中存储static变量。
方法区内存配置参数:-XX:PermSize和-XX:MaxPermSize
实例:
参数:-verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:PermSize=2M -XX:MaxPermSize=2M
代码:
public class RuntimeConstantPoolOOM {
public static void main(String[] args) {
try {
int i = 0;
List list = new ArrayList<>();
while (true) {
list.add(String.valueOf(i++).intern);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果:
Error occurred during initialization of VM
java.lang.OutOfMemoryError: PermGen space
at
at
从运行结果可以看出,运行时常量池属于方法区的一部分。