gpt4 book ai didi

java - PermGen 中的对象分配

转载 作者:行者123 更新时间:2023-11-30 07:14:47 25 4
gpt4 key购买 nike

我有一个关于 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();
}
}
}

谢谢

最佳答案

PermGen 空间主要包含反射数据。在运行时创建的对象通常存储在堆中,因此创建它们不应增加 PermGen 空间的大小。

但是(这只是一个猜测),如果您使用运行时织入或调用之前未被调用的方法(可能需要尚未加载的类),JVM 可能会将额外的反射数据加载到 PermGen 空间中(编织过程创建的方法、类、代理类等)。这可能是您遇到 PermGen 空间使用量增加的原因。

关于java - PermGen 中的对象分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18308664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com