/** * HeapOOM * Created by larry.su on 2017/2/7. * -Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError */ publicclassHeapOOM{ staticclassOOMObject{}
publicstaticvoidmain(String[] args){ List<OOMObject> list = new ArrayList<OOMObject>(); while (true) { list.add(new OOMObject()); } } }
运行结果:
1 2 3 4
java.lang.OutOfMemoryError: Java heap space Dumping heap to java_pid65766.hprof ... Heap dump file created [27784157 bytes in 0.137 secs] Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
Exception in thread "main" java.lang.StackOverflowError stackLength:744 at com.jvm.JavaVMStackSOF.stackLeak(JavaVMStackSOF.java:14) at com.jvm.JavaVMStackSOF.stackLeak(JavaVMStackSOF.java:15) at com.jvm.JavaVMStackSOF.stackLeak(JavaVMStackSOF.java:15)
/** * Returns a canonical representation for the string object. * <p> * A pool of strings, initially empty, is maintained privately by the * class {@code String}. * <p> * When the intern method is invoked, if the pool already contains a * string equal to this {@code String} object as determined by * the {@link #equals(Object)} method, then the string from the pool is * returned. Otherwise, this {@code String} object is added to the * pool and a reference to this {@code String} object is returned. * <p> * It follows that for any two strings {@code s} and {@code t}, * {@code s.intern() == t.intern()} is {@code true} * if and only if {@code s.equals(t)} is {@code true}. * <p> * All literal strings and string-valued constant expressions are * interned. String literals are defined in section 3.10.5 of the * <cite>The Java™ Language Specification</cite>. * * @return a string that has the same contents as this string, but is * guaranteed to be from a pool of unique strings. */ publicnative String intern();
/** * VM Args: -XX:PermSize=10M -XX:MaxPermSize=10M * Created by larry.su on 2017/2/17. */ publicclassRuntimeConstantsPoolOOM{ publicstaticvoidmain(String[] args)throws Throwable { //使用List保持常量池的引用,避免Full GC回收常量池行为 List<String> list = new ArrayList<String>(); //10M 的PermSize在Integer范围内足够产生OOM int i = 0; while (true) { try { list.add(String.valueOf(i++).intern()); } catch (Throwable e) { System.out.println(i); throw e; } } } }
运行结果:
1 2 3 4
86889 Exception in thread "main" java.lang.OutOfMemoryError: PermGen space at java.lang.String.intern(Native Method) at com.jvm.RuntimeConstantsPoolOOM.main(RuntimeConstantsPoolOOM.java:21)
在JDK1.7中运行这段代码就不会得到相同的接口,while会一直循环下去。
在JDK8中,while同样一直循环下去,同时控制台打印如下信息:
1 2
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=10M; support was removed in 8.0 Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=10M; support was removed in 8.0