Java calculates the size of an object that occupies memory

Source: Internet
Author: User


It is very simple to compute a basic type or an object's memory size in C + +, as long as the sizeof () operator in the library is called, but the Java API does not provide us with a similar method. So can we implement the sizeof () method in Java ourselves? The answer is yes. To calculate the memory size of a Java object, you first have to understand the memory structure of the Java object. If you don't understand it, read the Java memory structure first.

Let's start with the Sun.misc.Unsafe class, which is a magical class in Java, a collection of methods for performing low-level, unsafe operations. Although this class and all methods are public, the use of this class is still limited, and you cannot use the class directly in your own Java program, because its constructor is private.


More introduction and usage of unsafe class can be referred to http://mishadoff.github.io/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/

Package Size;import Java.lang.reflect.array;import Java.lang.reflect.field;import java.lang.reflect.Modifier; Import Sun.misc.unsafe;public class Unsafetest {/** the size of the object header */private static final int object_header_size = 8;/** object consumes the most memory Small value */private static final int minimum_object_size = 8;/** object is aligned by how many bytes of granularity */private static final int object_alignment = 8;p Ublic Static long sizeOf (Object obj) {//Get unsafe instance unsafe unsafe;try {Field Unsafefield = Unsafe.class.getDeclaredField (" Theunsafe "); Unsafefield.setaccessible (true); unsafe = (unsafe) unsafefield.get (null);} catch (Throwable t) {unsafe = null;} Determines whether an object is an array if (Obj.getclass (). IsArray ()) {class<?> Klazz = Obj.getclass (); int base = Unsafe.arraybaseoffset ( KLAZZ), int scale = Unsafe.arrayindexscale (Klazz), long size = base + (Scale * array.getlength (obj)), if ((Size% Object_alig nment)! = 0) {size + = object_alignment-(size% object_alignment);} Return Math.max (Minimum_object_size, SIZE);} else {//If the array object iterates through the object's parent class, it finds the offset for the last non-static field for (CLASS&Lt;? > Klazz = Obj.getclass (); Klazz! = NULL; Klazz = Klazz.getsuperclass ()) {Long Lastfieldoffset = -1;for (Field f:klazz.getdeclaredfields ()) {if (! Modifier.isstatic (F.getmodifiers ())) {Lastfieldoffset = Math.max (Lastfieldoffset,unsafe.objectfieldoffset (f));}} if (Lastfieldoffset > 0) {lastfieldoffset + = 1;if ((lastfieldoffset% object_alignment)! = 0) {Lastfieldoffset + = OBJEC t_alignment-(lastfieldoffset% object_alignment);} Return Math.max (Minimum_object_size, Lastfieldoffset);}} The object does not have any properties long size = object_header_size;if ((size% object_alignment)! = 0) {size + = object_alignment-(size% object_ ALIGNMENT);} Return Math.max (Minimum_object_size, SIZE);}} public static void Main (string[] args) throws Interruptedexception {Opusvoiceinfo voice = new Opusvoiceinfo (); Opusvoicein Fo Voicex = new Opusvoiceinfo (); Voicex.setopusid (8888888888888888888L); Voicex.setopusid2 (8888888888888888888L); VOICEX.SETOPUSID3 (8888888888888888888L); Voicex.setopusid4 (8888888888888888888L); OpusVoiceInfo2Voice2 = new OpusVoiceInfo2 (); System.out.println (Unsafetest.sizeof (voice));//Output System.out.println (unsafetest.sizeof (Voicex)); System.out.println ("Voice2:" + unsafetest.sizeof (VOICE2));//Output Thread.Sleep (100000);//blocking threads, in order to use the Jmap tool}}/**output : 7272voice2:56*/


Jmap View consistent: OK


Print out a Java process (using PID) in memory, all the ' objects ' in the case (e.g., which objects are produced, and their number).

A tool that can output all in-memory objects, and even the heap in the VM can be exported as text in binary. Use the method Jmap-histo pid. If you use the shell Jmap-histo Pid>a.log can save it to the text, after a period of time, using the text Comparison tool, you can compare what the GC recycled objects. Jmap-dump:format=b,file=outfile 3024 The memory heap of the 3024 process can be output to the outfile file, and with the Mat (Memory Analysis tool), use see: http ://blog.csdn.net/fenglibing/archive/2011/04/02/6298326.aspx) or with Jhat (Java Heap analysis Tool), The ability to visually display current memory in the form of an image is problematic.

The use of 64-bit machines requires the following methods:

Jmap-j-d64-heap PID

2. Command format

Synopsis

jmap [option] pid

jmap [option] executable core

jmap [option] [[Email Protected]]remote-hostname-or-ip

3. Parameter description

1) Options:

Executable Java executable from which, the core dump was produced.

(Probably the Java executable that generated the core dump)

Core dump file that will be printed with the information

Remote-hostname-or-ip the host name or IP of the Remote Debug service

Server-id Unique ID, if multiple Remote debug services on a single host

2) Basic parameters:

-dump:[live,]format=b,file=<filename> uses the Hprof binary form to output the JVM's heap content to File =. The live sub-option is optional, and if you specify the live option, only the live object is exported to the file.

-finalizerinfo prints information about objects that are waiting to be reclaimed.

-heap prints the summary of the heap, the algorithm used by the GC, the configuration of the heap, and the use of the wise heap.

-histo[:live] Prints the number of instances per class, memory consumption, class full name information. The internal class name of the VM is prefixed with "*". If the live child parameter is added, only the number of live objects is counted.

-permstat Prints the classload and JVM heap for a long layer of information. Contains the name of each classloader, the liveliness, the address, the parent ClassLoader, and the number of classes loaded. In addition, the number of internal strings and the amount of memory consumed are also printed.

-F coercion. Use the-dump or-histo parameters when the PID is not appropriate. In this mode, the live sub-argument is invalid.

-H | -HELP Printing Auxiliary Information

-j Pass parameters to Jmap-initiated JVM.

The PID needs to be printed with the information of the Java process ID, the difference between entrepreneurship and work-blog preview, you can use JPS to inquire.

4. Examples of Use

1) [[email protected] ~]$ Jmap-histo 4939

[Output more not posted here]

2) [[email protected] ~]$ Jmap-dump:format=b,file=test.bin 4939

Dumping Heap To/home/fenglb/test.bin ...

Heap dump file created






Java calculates the size of an object that occupies memory

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.