Heim  >  Fragen und Antworten  >  Hauptteil

JAVA如何查看HttpRequest和HttpResponse占用的内存大小?

如题,“如何输出HttpRequest和HttpResponse对象占内存的大小”?
网上说,利用java.lang.Instrumentation的API来计算,我调用了提供的一个工具类,但是报NullPointerException异常:

进一步分析,应该是实例化Instrumentation的premain()方法没有被JVM调用。
应该通过“ -javaagent”命令来调用,不知道应该如何调。

PHP中文网PHP中文网2712 Tage vor415

Antworte allen(1)Ich werde antworten

  • 天蓬老师

    天蓬老师2017-04-17 17:24:33

    把下面的类编译好放到ObjectSizeFetcherAgent.jar中

    import java.lang.instrument.Instrumentation;
    public class ObjectSizeFetcher {
        private static Instrumentation instrumentation;
        public static void premain(String args, Instrumentation inst) {
            instrumentation = inst;
        }
        public static long getObjectSize(Object o) {
            return instrumentation.getObjectSize(o);
        }
    }
    

    在MANIFEST.MF中加入:

    Premain-Class: ObjectSizeFetcher
    

    然后写个test类

    public class C {
        private int x;
        private int y;
    
        public static void main(String [] args) {
            System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
        }
    }
    

    在命令行中这样执行:

    java -javaagent:ObjectSizeFetcherAgent.jar C

    Antwort
    0
  • StornierenAntwort