在jdk1.8的环境下模拟永久代内存溢出

相信很多小伙伴在看深刻理解Java虚拟机的时候,做者给咱们举例一个demo来发生PermGen spaceexpress

一、经过List不断添加String.intern();this

二、经过设置对应的-XX:PermSize与-XX:MaxPermSize(更快看到效果),spa

三、在jdk1.6的环境下会抛出OOM:PermGen space异常对象

public static void main(String[] args) {
    List<String> str=new ArrayList<>();
    int i=0;
    while (true){
        str.add(String.valueOf(i).intern());
    }

}

然而在jdk1.8的环境下,这段代码,会出现OOM,但不是出现PermGenSpace,而是会当堆内存不够用(-Xmx)的时候,抛出Java heap space,并且会舒适提示内存

ignoring option PermSize=10M; support was removed in 8.0ci

ignoring option MaxPermSize=10M; support was removed in 8.0rem

---------------------------------------------------------------------------------------------------------字符串

首先咱们看一下String.intern()方法,官方的注释是虚拟机

Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java? Language Specification.string

大概意思就是,若是常量池已经存在这个string对象,那么就返回这个字符串的引用。不然将此string对象加入常量池,再返回引用

~

可是在jdk1.8中,其实已经没有永久代这一说了,取而代之的是一个叫元空间(Meta space)。而常量池放到了堆中,因此也就不会出现PermGen space了

---------------------------------------------------------------------------------------------------------

那么若是想看到metaspace的异常怎么作呢?

一个是能够把这两个值设置的足够小,那么启动就会报错了。

-XX:MetaspaceSize=3M -XX:MaxMetaspaceSize=3M

一个是能够使用jdk动态加载技术,例如cglib动态的生成大量的数据来达到

相关文章
相关标签/搜索