Get the amount of memory the Java object occupies

Source: Internet
Author: User

Describes two ways to get the memory size of Java objects.

The first type: instrumentation

Brief introduction:

Use Java.lang.instrument's instrumentation to get the memory size of an object. By using instrumentation and by acting we can monitor the function of the program running in the JVM, it is the principle of modifying the bytecode of the method.

first create the proxy class

 Packagecom.dingtongblog.size;Importjava.lang.instrument.Instrumentation; Public classObjectsize {Private Static volatileinstrumentation Instru;  Public Static voidPremain (String args, Instrumentation inst) {Instru=Inst; }      Public StaticLong getsizeof (Object object) {if(Instru = =NULL) {            Throw NewIllegalStateException ("Instrumentation is null"); }        returninstru.getobjectsize (object); }}
Premain method: The JVM will call this method first. With this method we can initialize the property Instru successfully, and we get the size of an object by instrumentation's Getobjectsize (Object object) method.

and then package this class into a jar package .First we're going to create a manifest.txt and add such a line
Premain-class:com.dingtongblog.size.objectsize
This premain-class specifies which is the proxy class, that is, the class that includes the Premain method. Then pack the objectsize into a jar package.
JAVA-CMF manifest.txt Simplesize.jar com/dingtongblog/size/objectsize. class

Run

The jar is then introduced into the project, and the start parameter is added
-javaagent:jarpath[=options]
Executing at the command line
Java-javaagent:simplesize.jar Testmain

(Current Testmain and Simplesize.jar in the same directory)

The test code is as follows:

Import com.dingtongblog.size.ObjectSize;  Public class Testmain {publicstaticvoidnew  String (AA); System.out.println (Objectsize.getsizeof (a)); }

Output 24 We modify the parameter astring a = AA; Change to string a = AAAA;     Then run main, or output 24. Why doesn't the value change? Although the object a points to has changed, the output value is still 24 unchanged. This is because the memory size of the object itself, which is obtained using the Getsizeof method, does not contain the size of the object to which the property in the object points. In StringA total of 3 in a intproperty, a reference to an array, plus the number of bytes in the object header is 3 * 4 + 4 +8 = 24, then 24 is exactly a multiple of 8, and no padding bytes are required. So the direct output is 24. Is there a way to fetch the full number of bytes of an object? One idea is to iterate through each of the properties in the object, then call the above method to get the size of each object, and repeat the process until the last point is the basic type. Directly refer to the JAR package in this article. Introduce the package, and when you start the JVM, add the parameters

?
-javaagent:d:\sizeofag.jar

Test code:

?
 Public class Testmain {      publicstaticvoidthrows  illegalaccessexception {           New String (AA);        System.out.println (Sizeofagent.fullsizeof (a));        System.out.println (Sizeofagent.sizeof (a));  

You can see the result of the output 40,24

40 is the full size of this object. The first is the 12 bytes + two character byte of the 24 byte + Array object header computed earlier 2*2 can get 24+12+4 = 40. 40 is a multiple of 8 and does not require padding bytes. The second kind is jmap, jhat command.Jmap can output the details of a heap in a given program.
Jmap-histo <pid>  (PID is the ID of the current Java process)

For example
Jmap-histo 20230

This will directly output the details of the current heap, but this is not intuitive. Pass

The Java heap can be exported to a file in Hprof binary format, and then viewed through the jhat command, Jhat generates a page that provides a more intuitive view of the heap details. However, the memory space required by Jhat is several times the dump file, and if the dump file compares to an oom error, the heap information can be browsed through the mat.

For example
Jmap-dump:format=b,file=d:\dump.txt

And then through

Jhat filename;

(filename is a previously dump file) will parse the Java heap dump file and start a Web server, the default port of the server is 7000, after the command is finished, you can access the heap details through 127.0.0.1:7000.

Jhat D:\dump.txt

You can get a page like this. However, the results obtained by this method are not the same as those obtained by the previous instrumentation method. This place may calculate the method to have the difference, the individual thinks the instrumentation result will be more accurate, but has not found the relevant information to explain this question. Also use the Jprofiler tool to monitor the details of memory usage. Information:Http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html Instrumentation Introductionhttp://www.javamex.com/tutorials/memory/instrumentation.shtml instrumentation Use

Http://docs.oracle.com/javase/6/docs/technotes/tools/share/jmap.html Jamp IntroductionHttp://docs.oracle.com/javase/6/docs/technotes/tools/share/jhat.html Jhat Introduction

Get the amount of memory the Java object occupies

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.