How much memory is occupied by a Java object?

Source: Internet
Author: User

I recently read "deep understanding of Java virtual machines" and have a better understanding of the memory layout of Java objects, So I naturally have a very common problem in my mind, is how much memory does a Java object occupy? I found a blog posted on the Internet and talked about it very well: http://yueyemaitian.iteye.com/blog/2033046. This category is also very similar: copy the code import java. lang. instrument. instrumentation; import java. lang. reflect. array; import java. lang. reflect. field; import java. lang. reflect. modifier; import java. util. arrayDeque; import java. util. deque; import java. util. hashSet; import java. util. set;/*** tool class for byte usage of objects ** @ author tianmai. fh * @ date 2014-03-18 11: 29 */public c Lass SizeOfObject {static Instrumentation inst; public static void premain (String args, Instrumentation instP) {inst = instP;}/*** directly calculates the space occupied by the current object, including the basic instance field size of the current class and super class, <br> </br> * Reference size of the Instance field of the reference type, total space occupied by the instance basic type array, and instance reference type array reference the space occupied by it; <br> </br> * but does not include the size of the object inherited by the superclass and the instance reference field of the current class declaration, and the size of the object referenced by the instance reference array <br> </br> ** @ param obj * @ return */public static long sizeOf (Object obj) {return inst. getObjectSize (obj) ;}/*** Recursively calculates the total space occupied by the current object, including the instance field size of the current class and super class and the size of the Instance field reference Object ** @ param objP * @ return * @ throws IllegalAccessException */public static long fullSizeOf (Object objP) throws IllegalAccessException {Set <Object> visited = new HashSet <Object> (); Deque <Object> toBeQueue = new ArrayDeque <Object> (); toBeQueue. add (objP); long size = 0L; while (toBeQueue. size ()> 0) {Object obj = toBeQueue. poll (); // sizeOf has The basic type and reference length, including array size + = skipObject (visited, obj )? 0L: sizeOf (obj); Class <?> TmpObjClass = obj. getClass (); if (tmpObjClass. isArray () {// [I, [F basic type name length is 2 if (tmpObjClass. getName (). length ()> 2) {for (int I = 0, len = Array. getLength (obj); I <len; I ++) {Object tmp = Array. get (obj, I); if (tmp! = Null) {// The object toBeQueue. add (Array. get (obj, I) needs to be traversed in depth for non-basic types; }}} else {while (tmpObjClass! = Null) {Field [] fields = tmpObjClass. getDeclaredFields (); for (Field field: fields) {if (Modifier. isStatic (field. getModifiers () // static | field. getType (). isPrimitive () {// the basic type is continuous;} field. setAccessible (true); Object fieldValue = field. get (obj); if (fieldValue = null) {continue;} toBeQueue. add (fieldValue);} tmpObjClass = tmpObjClass. getSuperclass () ;}}return size;}/*** St Ring. intern objects are excluded; computing objects are excluded, and endless loops are also avoided ** @ param visited * @ param obj * @ return */static boolean skipObject (Set <Object> visited, object obj) {if (obj instanceof String & obj = (String) obj ). intern () {return true;} return visited. contains (obj) ;}} you can use this code to view and verify the code. Note that you need to inject Instrumentation into the Java agent to run this program. For details, refer to the original blog. Today I will summarize the basic rules for manually calculating the number of bytes occupied by Java objects. As a basic skill, I must get √. I hope this will help me with the same Java cainiao. Before the introduction, let's briefly review the memory layout of Java objects: Object headers, Instance Data, and Padding. For details, see my reading notes. In addition, the results of different environments may be different. My environment is a HotSpot virtual machine and a 64-bit Windwos. Enter the text below: the object header occupies 8 bytes on 32-bit systems, and 16 bytes on 64-bit systems. The Memory usage of the instance data native type (primitive Type) is as follows: Primitive type Memory Required (bytes) boolean 1 byte 1 short 2 char 2int 4 float 4 long 8 double 8reference type occupies 4 bytes for each 32-bit system and 8 bytes for each 64-bit system. The alignment of padding HotSpot is 8-byte alignment: (Object Header + instance data + padding) % 8 is equal to 0 and the memory size occupied by 0 <= padding <8 pointer compression objects is affected by the VM parameter UseCompressedOops. 1) The impact on the object header is enabled (-XX: + UseCompressedOops). The object header size is 12 bytes (64-bit machine ). Static class A {int a;} memory usage of object A: Disable pointer compression: 16 + 4 = 20 is not A multiple of 8, so + padding/4 = 24 enable pointer compression: 12 + 4 = 16 is a multiple of 8, and no additional padding is required. 1) Impact on the reference type 64-bit reference type occupies 8 bytes, and 4 bytes after enabling pointer compression. Static class B2 {int b2a; Integer B2B;} memory usage of B2 objects: Disable pointer compression: 16 + 4 + 8 = 28 is not a multiple of 8, so + padding/4 = 32 enable pointer compression: 12 + 4 + 4 = 20 is not a multiple of 8, so + padding/4 = 24 array object on 64-bit machines, the object header of the array object occupies 24 bytes, and 16 bytes after compression is enabled. The reason for occupying more memory than ordinary objects is that extra space is required to store the length of the array. First consider the memory size occupied by new Integer [0]. The length is 0, that is, the size of the object header: Disabled compression: 24 bytes after enabling compression: 16 bytes: Calculate new Integer [1], new Integer [2], new Integer [3], and new Integer [4]. It is easy: compression is not enabled: compression is Enabled: take new Integer [3] For details: Compression not enabled: 24 (object header) + 8*3 = 48, no padding required; Enable compression: 16 (object header) + 3*4 = 28, + padding/4 = 32, and so on. The same is true for arrays of custom classes, such as static class B3 {int a; Integer B;} memory size occupied by new B3 [3]: compression disabled: after 48 compression is Enabled: 32 composite objects calculate the memory usage of composite objects by using the above rules, which is only a hassle. 1) The size of the object directly calculates the space occupied by the current object, including the basic instance field size of the current class and super class, the reference size of the Instance field of the reference type, the total occupied space of the Instance basic type array, and the occupied space of the Instance reference type array reference itself; however, this does not include the size of the objects inherited by the superclass and the instance reference field of the current class declaration, and the size of the objects referenced by the instance reference array. Copy the code static class B {int a; int B;} static class C {int ba; B [] as = new B [3]; C () {for (int I = 0; I <. length; I ++) {as [I] = new B () ;}} the copied Code has not been compressed: 16 (object header) + 4 (ba) + 8 (as reference size) + padding/4 = 32 enable compression: 12 + 4 + 4 + padding/4 = 24 2) the total size of the space occupied by the current object recursively calculates the total size of the space occupied by the current object, including the instance field size of the current class and the super class, and the size of the Instance field reference object. When recursively calculating the memory occupied by a composite object, you must note that alignment filling is performed in units of each object. It is easy to understand the following figure. Now we can manually calculate the total memory occupied by the C object, which is mainly composed of three parts: the size of the C object itself, the size of the array object, and the size of the B object. Compression not enabled: (16 + 4 + 8) + (24 + 8*3) + (16 + 8) * 3 + 4 (padding) = 152 bytes enable compression: (12 + 4 + 4) + (16 + 4*3 + 4 (array object padding) + (12 + 8 + 4 (B object padding )) * 3 + 4 (padding) = 128 bytes anyone interested can try. In actual work, there should be very few scenarios that really need to manually calculate the object size. However, I personally think that every Java developer should understand the basic knowledge. In addition, the amount of memory occupied by self-written code is about, the memory layout should have an intuitive understanding.

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.