The simplest way to add content to a running constant pool is to use the String.intern () Native method. The function of this method is that if the pool already contains a string equal to this string object, a String object representing the string in the pool is returned, otherwise the string contained in this string object is added to the constant pool, and a reference to this string object is returned. Because the constant pool is allocated within the method area, we can limit the size of the method area through-xx:permsize and-xx:maxpermsize, thereby indirectly limiting the memory overflow exception caused by the capacity code of the constant pool running the frequent pool.
/** * VM Args: -XX:PermSize=10M -XX:MaxPermSize=10M */public class RuntimeConstantPoolOOM { public static void main(String[] args) { // 使用 List 保持着常量池引用,避免 Full GC 回收常量池行为 List<String> list = new ArrayList<String>(); // 10MB 的 PermSize 在 integer 范围内足够产生 OOM 了 int i = 0; while (true) { list.add(String.valueOf(i++).intern()); } }}
Operation Result:
in"main" java.lang.OutOfMemoryError: PermGen spaceat java.lang.String.intern(Native Method)at org.fenixsoft.oom.RuntimeConstantPoolOOM.main(RuntimeConstantPoolOOM.java:18)
As you can see from the running results, the run-time pool overflow, followed by OutOfMemoryError, is "permgenspace", indicating that the run-time pool is part of the method area (the permanent generation in the HotSpot virtual machine).
Java Virtual machine Oom runtime frequent pool overflow (5)