Home  >  Q&A  >  body text

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

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

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

PHP中文网PHP中文网2712 days ago417

reply all(1)I'll reply

  • 天蓬老师

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

    Compile the following class and put it in 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);
        }
    }
    

    Add to MANIFEST.MF:

    Premain-Class: ObjectSizeFetcher
    

    Then write a test class

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

    Execute like this in the command line:

    java -javaagent:ObjectSizeFetcherAgent.jar C

    reply
    0
  • Cancelreply