2013-04-21 65 views
6

我用Java反射在这样的代码:java.lang.OutOfMemoryError:PermGen的空间:Java反射

Method method = LogFactory.class.getDeclaredMethod("getContextClassLoader"); 
method.setAccessible(true); 
ClassLoader classLoader = (ClassLoader)method.invoke(null); 
LogFactory.release(classLoader); 

我用jprofiler可以看到这样sun.reflect.GeneratedMethodAccessor11

这些类每增加了许多类电话

sun.reflect.BootstrapConstructorAccessorImpl 
sun.reflect.NativeConstructorAccessorImpl 
sun.reflect.DelegatingConstructorAccessorImpl 
sun.reflect.DelegatingClassLoader 

我想这就是为什么PermGen空间增加了,如何清理这些类?

+0

为什么不创造更多的烫发空间? – StarPinkER 2013-04-21 10:41:31

+0

也许我应该做更多的测试,我使用eclipse调试代码和jprofiler附加它。 – Fatkun 2013-04-21 10:45:11

+0

@JermaineXu默认的perm空间是128MB,但它在一个月后达到了 – Fatkun 2013-04-21 10:48:14

回答

10

有一篇相当不错的文章,讨论关于potential native memory use in reflection delegating classloaders

When using Java reflection, the JVM has two methods of accessing the information on the class being reflected. It can use a JNI accessor, or a Java bytecode accessor. If it uses a Java bytecode accessor, then it needs to have its own Java class and classloader (sun/reflect/GeneratedMethodAccessor class and sun/reflect/DelegatingClassLoader). Theses classes and classloaders use native memory. The accessor bytecode can also get JIT compiled, which will increase the native memory use even more. If Java reflection is used frequently, this can add up to a significant amount of native memory use. The JVM will use the JNI accessor first, then after some number of accesses on the same class, will change to use the Java bytecode accessor. This is called inflation, when the JVM changes from the JNI accessor to the bytecode accessor. Fortunately, we can control this with a Java property. The sun.reflect.inflationThreshold property tells the JVM what number of times to use the JNI accessor. If it is set to 0, then the JNI accessors are always used. Since the bytecode accessors use more native memory than the JNI ones, if we are seeing a lot of Java reflection, we will want to use the JNI accessors. To do this, we just need to set the inflationThreshold property to zero.

设置sun.reflect.inflationThreshold 0通过-Dsun.reflect.inflationThreshold=0会做的技巧你。

+1

-Dsun.reflect.inflationThreshold = 0将使所有调用使用GeneratedMethodAccessor(jdk6u51 macosx mountain lion)。将它设置为一个很大的值(Integer.MAX_VALUE)将会很好。 – 2013-09-25 12:16:47

1

如果你是一个甲骨文JVM那么只需要设置:

sun.reflect.inflationThreshold=2147483647 

如果您对IBM JVM,那么你就需要设置:

-Dsun.reflect.inflationThreshold=0 

请注意,两个JVM在解释方式上都有所不同。

了解更多详情参考:

inflation_system_properties

native memory use