我对 PermGen 中的内存分配过多有疑问。
我写了一个小代码来监控这个内存空间的大小,我注意到几乎每个方法执行后分配的内存大小都会增加。也许我的应用程序中有很多全局对象?有没有办法知道在 PermGen 中分配了哪些对象?目前我只知道已用内存的大小。
这是我编写的代码,定义为在每次方法调用后执行的建议:
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
import java.util.Iterator;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
@Aspect
public class PermGenStat {
static Long bytesPrecedenti = getUsedPermGenBytes();
private static Long getUsedPermGenBytes() {
Long bytes = 0L;
Iterator<MemoryPoolMXBean> iter = ManagementFactory.getMemoryPoolMXBeans().iterator();
while (iter.hasNext()) {
MemoryPoolMXBean item = (MemoryPoolMXBean) iter.next();
if (item.getName().equals("PS Perm Gen"))
bytes = item.getUsage().getUsed();
}
return bytes;
}
@AfterReturning (pointcut = "execution(* it.xxx.yyy.*.*.*.*(..))",
returning = "result")
public void afterReturning (JoinPoint joinPoint, Object result) {
if (joinPoint != null &&
joinPoint.getTarget() != null &&
joinPoint.getTarget().getClass() != null &&
joinPoint.getSignature() != null &&
joinPoint.getSignature().getName() != null) {
try {
Long bytes = getUsedPermGenBytes();
Long diff = bytes - bytesPrecedenti;
if (diff >= 1) {
System.out.println("Metodo: " + joinPoint.getTarget().getClass().toString().substring(6) + "." + joinPoint.getSignature().getName().toString());
System.out.println("PermGen (KB): " + Math.round((double)bytesPrecedenti / 1024) + " -> " +
Math.round((double)bytes / 1024) +
" [" + Math.round((double)diff / 1024) + "]");
}
bytesPrecedenti = bytes;
}
catch (Exception e) {
System.out.println("******************** Eccezione ********************");
System.out.println("Classe: PermGenStat - Metodo: afterReturning");
e.printStackTrace();
}
}
}
}
谢谢