Java中对象占用内存计算方法

普通对象的结构如下,按64位机器的长度计算

1. 对象头(_mark), 8个字节

2. Oop指针,如果是32G内存以下的,默认开启对象指针压缩,4个字节

3. 数据区

4.Padding(内存对齐),按照8的倍数对齐

数组对象结构是

1. 对象头(_mark), 8个字节

2. Oop指针,如果是32G内存以下的,默认开启对象指针压缩,4个字节

3. 数组长度,4个字节

4. 数据区

5. Padding(内存对齐),按照8的倍数对齐

清楚了对象在内存的基本布局后,咱们说两种计算Java对象大小的方法

1. 通过java.lang.instrument.Instrumentation的getObjectSize(obj)直接获取对象的大小

2. 通过sun.misc.Unsafe对象的objectFieldOffset(field)等方法结合反射来计算对象的大小

java.lang.instrument.Instrumentation.getObjectSize()的方式

先讲讲java.lang.instrument.Instrumentation.getObjectSize()的方式,这种方法得到的是Shallow Size,即遇到引用时,只计算引用的长度,不计算所引用的对象的实际大小。如果要计算所引用对象的实际大小,可以通过递归的方式去计算。

java.lang.instrument.Instrumentation的实例必须通过指定javaagent的方式才能获得,具体的步骤如下:

1. 定义一个类,提供一个premain方法: public static void premain(String agentArgs, Instrumentation instP)

2. 创建META-INF/MANIFEST.MF文件,内容是指定PreMain的类是哪个: Premain-Class: sizeof.ObjectShallowSize

3. 把这个类打成jar,然后用java -javaagent XXXX.jar XXX.main的方式执行

下面先定义一个类来获得java.lang.instrument.Instrumentation的实例,并提供了一个static的sizeOf方法对外提供Instrumentation的能力

[java] 
 
  1. package sizeof;  
  2.   
  3. import java.lang.instrument.Instrumentation;  
  4.   
  5. public class ObjectShallowSize {  
  6.     private static Instrumentation inst;  
  7.       
  8.     public static void premain(String agentArgs, Instrumentation instP){  
  9.         inst = instP;  
  10.     }  
  11.       
  12.     public static long sizeOf(Object obj){  
  13.         return inst.getObjectSize(obj);  
  14.     }  
  15. }  

定义META-INF/MANIFEST.MF文件

[java] 
 
  1. Premain-Class: sizeof.ObjectShallowSize  


打成jar包

[html] 
 
  1. cd 编译后的类和META-INF文件夹所在目录  
  2. jar cvfm java-agent-sizeof.jar META-INF/MANIFEST.MF  .  


准备好了这个jar之后,我们可以写测试类来测试Instrumentation的getObjectSize方法了。在这之前我们先来看对象在内存中是按照什么顺序排列的

有如下这个类,字段的定义按如下顺序

[java]
 
  1. private static class ObjectA {  
  2.         String str;  // 4  
  3.         int i1; // 4  
  4.         byte b1; // 1  
  5.         byte b2; // 1  
  6.         int i2;  // 4   
  7.         ObjectB obj; //4  
  8.         byte b3;  // 1  
  9.     }  


按照我们之前说的方法来计算一下这个对象所占大小,注意按8对齐

8(_mark) + 4(oop指针) + 4(str) + 4(i1) + 1(b1) + 1(b2) + 2(padding) + 4(i2) + 4(obj) + 1(b3) + 7(padding) = 40 ?

但事实上是这样的吗? 我们来用Instrumentation的getObjectSize来计算一下先:

[java]  
 
  1. package test;  
  2.   
  3. import sizeof.ObjectShallowSize;  
  4.   
  5. public class SizeofWithInstrumetation {  
  6.     private static class ObjectA {  
  7.         String str;  // 4  
  8.         int i1; // 4  
  9.         byte b1; // 1  
  10.         byte b2; // 1  
  11.         int i2;  // 4   
  12.         ObjectB obj; //4  
  13.         byte b3;  // 1  
  14.     }  
  15.       
  16.     private static class ObjectB {  
  17.           
  18.     }  
  19.       
  20.     public static void main(String[] args){  
  21.         System.out.println(ObjectShallowSize.sizeOf(new ObjectA()));  
  22.     }  
  23. }  


得到的结果是32!不是会按8对齐吗,b3之前的数据加起来已经是32了,多了1个b3,为33,应该对齐到40才对啊。事实上,HotSpot创建的对象的字段会先按照给定顺序排列一下,默认的顺序如下,从长到短排列,引用排最后:  long/double --> int/float -->  short/char --> byte/boolean --> Reference

这个顺序可以使用JVM参数:  -XX:FieldsAllocationSylte=0(默认是1)来改变。

我们使用sun.misc.Unsafe对象的objectFieldOffset方法来验证一下:

[java]  
 
  1. Field[] fields = ObjectA.class.getDeclaredFields();  
  2.         for(Field f: fields){  
  3.             System.out.println(f.getName() + " offset: " +unsafe.objectFieldOffset(f));  
  4.         }  


可以看到确实是按照从长到短,引用排最后的方式在内存中排列的。按照这种方法我们来重新计算下ObjectA创建的对象的长度:

8(_mark) + 4(oop指针) + 4(i1) + + 4(i2) + 1(b1) + 1(b2) + 1(b3) + 1(padding) +  4(str) + 4(obj) = 32

得到的结果和java.lang.instrument.Instrumentation.getObjectSize()的结果是一样的,证明我们的计算方式是正确的。

sun.misc.Unsafe的方式

下面说一下通过sun.misc.Unsafe对象的objectFieldOffset(field)等方法结合反射来计算对象的大小。基本的思路如下:

1. 通过反射获得一个类的Field

2. 通过Unsafe的objectFieldOffset()获得每个Field的offSet

3. 对Field按照offset排序,取得最大的offset,然后加上这个field的长度,再加上Padding对齐

上面三步就可以获得一个对象的Shallow size。可以进一步通过递归去计算所引用对象的大小,从而可以计算出一个对象所占用的实际大小。

如何获得Unsafe对象已经在这篇中聊聊序列化(二)使用sun.misc.Unsafe绕过new机制来创建Java对象说过了,可以通过反射的机制来获得.

Oop指针是4还是未压缩的8也可以通过unsafe.arrayIndexScale(Object[].class)来获得,这个方法返回一个引用所占用的长度

[java]  
 
  1. static {  
  2.         try {  
  3.             Field field = Unsafe.class.getDeclaredField("theUnsafe");  
  4.             field.setAccessible(true);  
  5.             unsafe = (Unsafe) field.get(null);  
  6.   
  7.             objectRefSize = unsafe.arrayIndexScale(Object[].class);  
  8.         } catch (Exception e) {  
  9.             throw new RuntimeException(e);  
  10.         }  
  11.     }  


下面的源码摘自 http://java-performance.info/memory-introspection-using-sun-misc-unsafe-and-reflection/, 原文中的代码在计算对象大小的时候有问题,我做了微调,并加上了内存对齐的方法,这样计算出的结果和Instrumentation的getObjectSize方法是一样的。

[java]  
 
  1. package test;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collections;  
  5. import java.util.Comparator;  
  6. import java.util.List;  
  7.    
  8. /** 
  9.  * This class contains object info generated by ClassIntrospector tool 
  10.  */  
  11. public class ObjectInfo {  
  12.     /** Field name */  
  13.     public final String name;  
  14.     /** Field type name */  
  15.     public final String type;  
  16.     /** Field data formatted as string */  
  17.     public final String contents;  
  18.     /** Field offset from the start of parent object */  
  19.     public final int offset;  
  20.     /** Memory occupied by this field */  
  21.     public final int length;  
  22.     /** Offset of the first cell in the array */  
  23.     public final int arrayBase;  
  24.     /** Size of a cell in the array */  
  25.     public final int arrayElementSize;  
  26.     /** Memory occupied by underlying array (shallow), if this is array type */  
  27.     public final int arraySize;  
  28.     /** This object fields */  
  29.     public final List<ObjectInfo> children;  
  30.    
  31.     public ObjectInfo(String name, String type, String contents, int offset, int length, int arraySize,  
  32.     int arrayBase, int arrayElementSize)  
  33.     {  
  34.         this.name = name;  
  35.         this.type = type;  
  36.         this.contents = contents;  
  37.         this.offset = offset;  
  38.         this.length = length;  
  39.         this.arraySize = arraySize;  
  40.         this.arrayBase = arrayBase;  
  41.         this.arrayElementSize = arrayElementSize;  
  42.         children = new ArrayList<ObjectInfo>( 1 );  
  43.     }  
  44.    
  45.     public void addChild( final ObjectInfo info )  
  46.     {  
  47.         if ( info != null )  
  48.             children.add( info );  
  49.     }  
  50.    
  51.     /** 
  52.     * Get the full amount of memory occupied by a given object. This value may be slightly less than 
  53.     * an actual value because we don't worry about memory alignment - possible padding after the last object field. 
  54.     * 
  55.     * The result is equal to the last field offset + last field length + all array sizes + all child objects deep sizes 
  56.     * @return Deep object size 
  57.     */  
  58.     public long getDeepSize()  
  59.     {  
  60.         //return length + arraySize + getUnderlyingSize( arraySize != 0 );  
  61.         return addPaddingSize(arraySize + getUnderlyingSize( arraySize != 0 ));  
  62.     }  
  63.    
  64.     long size = 0;  
  65.       
  66.     private long getUnderlyingSize( final boolean isArray )  
  67.     {  
  68.         //long size = 0;  
  69.         for ( final ObjectInfo child : children )  
  70.             size += child.arraySize + child.getUnderlyingSize( child.arraySize != 0 );  
  71.         if ( !isArray && !children.isEmpty() ){  
  72.             int tempSize = children.get( children.size() - 1 ).offset + children.get( children.size() - 1 ).length;  
  73.             size += addPaddingSize(tempSize);  
  74.         }  
  75.               
  76.         return size;  
  77.     }  
  78.    
  79.     private static final class OffsetComparator implements Comparator<ObjectInfo>  
  80.     {  
  81.         @Override  
  82.         public int compare( final ObjectInfo o1, final ObjectInfo o2 )  
  83.         {  
  84.             return o1.offset - o2.offset; //safe because offsets are small non-negative numbers  
  85.         }  
  86.     }  
  87.    
  88.     //sort all children by their offset  
  89.     public void sort()  
  90.     {  
  91.         Collections.sort( children, new OffsetComparator() );  
  92.     }  
  93.    
  94.     @Override  
  95.     public String toString() {  
  96.         final StringBuilder sb = new StringBuilder();  
  97.         toStringHelper( sb, 0 );  
  98.         return sb.toString();  
  99.     }  
  100.    
  101.     private void toStringHelper( final StringBuilder sb, final int depth )  
  102.     {  
  103.         depth( sb, depth ).append("name=").append( name ).append(", type=").append( type )  
  104.             .append( ", contents=").append( contents ).append(", offset=").append( offset )  
  105.             .append(", length=").append( length );  
  106.         if ( arraySize > 0 )  
  107.         {  
  108.             sb.append(", arrayBase=").append( arrayBase );  
  109.             sb.append(", arrayElemSize=").append( arrayElementSize );  
  110.             sb.append( ", arraySize=").append( arraySize );  
  111.         }  
  112.         for ( final ObjectInfo child : children )  
  113.         {  
  114.             sb.append( ' ' );  
  115.             child.toStringHelper(sb, depth + 1);  
  116.         }  
  117.     }  
  118.    
  119.     private StringBuilder depth( final StringBuilder sb, final int depth )  
  120.     {  
  121.         for ( int i = 0; i < depth; ++i )  
  122.             sb.append( " ");  
  123.         return sb;  
  124.     }  
  125.       
  126.     private long addPaddingSize(long size){  
  127.         if(size % 8 != 0){  
  128.             return (size / 8 + 1) * 8;  
  129.         }  
  130.         return size;  
  131.     }  
  132.       
  133. }  
  134.   
  135.   
  136. package test;  
  137.   
  138. import java.lang.reflect.Array;  
  139. import java.lang.reflect.Field;  
  140. import java.lang.reflect.Modifier;  
  141. import java.util.ArrayList;  
  142. import java.util.Arrays;  
  143. import java.util.Collections;  
  144. import java.util.HashMap;  
  145. import java.util.IdentityHashMap;  
  146. import java.util.List;  
  147. import java.util.Map;  
  148.   
  149. import sun.misc.Unsafe;  
  150.   
  151. /** 
  152.  * This class could be used for any object contents/memory layout printing. 
  153.  */  
  154. public class ClassIntrospector {  
  155.   
  156.     private static final Unsafe unsafe;  
  157.     /** Size of any Object reference */  
  158.     private static final int objectRefSize;  
  159.     static {  
  160.         try {  
  161.             Field field = Unsafe.class.getDeclaredField("theUnsafe");  
  162.             field.setAccessible(true);  
  163.             unsafe = (Unsafe) field.get(null);  
  164.   
  165.             objectRefSize = unsafe.arrayIndexScale(Object[].class);  
  166.         } catch (Exception e) {  
  167.             throw new RuntimeException(e);  
  168.         }  
  169.     }  
  170.   
  171.     /** Sizes of all primitive values */  
  172.     private static final Map<Class, Integer> primitiveSizes;  
  173.   
  174.     static {  
  175.         primitiveSizes = new HashMap<Class, Integer>(10);  
  176.         primitiveSizes.put(byte.class, 1);  
  177.         primitiveSizes.put(char.class, 2);  
  178.         primitiveSizes.put(int.class, 4);  
  179.         primitiveSizes.put(long.class, 8);  
  180.         primitiveSizes.put(float.class, 4);  
  181.         primitiveSizes.put(double.class, 8);  
  182.         primitiveSizes.put(boolean.class, 1);  
  183.     }  
  184.   
  185.     /** 
  186.      * Get object information for any Java object. Do not pass primitives to 
  187.      * this method because they will boxed and the information you will get will 
  188.      * be related to a boxed version of your value. 
  189.      *  
  190.      * @param obj 
  191.      *            Object to introspect 
  192.      * @return Object info 
  193.      * @throws IllegalAccessException 
  194.      */  
  195.     public ObjectInfo introspect(final Object obj)  
  196.             throws IllegalAccessException {  
  197.         try {  
  198.             return introspect(obj, null);  
  199.         } finally { // clean visited cache before returning in order to make  
  200.                     // this object reusable  
  201.             m_visited.clear();  
  202.         }  
  203.     }  
  204.   
  205.     // we need to keep track of already visited objects in order to support  
  206.     // cycles in the object graphs  
  207.     private IdentityHashMap<Object, Boolean> m_visited = new IdentityHashMap<Object, Boolean>(  
  208.             100);  
  209.   
  210.     private ObjectInfo introspect(final Object obj, final Field fld)  
  211.             throws IllegalAccessException {  
  212.         // use Field type only if the field contains null. In this case we will  
  213.         // at least know what's expected to be  
  214.         // stored in this field. Otherwise, if a field has interface type, we  
  215.         // won't see what's really stored in it.  
  216.         // Besides, we should be careful about primitives, because they are  
  217.         // passed as boxed values in this method  
  218.         // (first arg is object) - for them we should still rely on the field  
  219.         // type.  
  220.         boolean isPrimitive = fld != null && fld.getType().isPrimitive();  
  221.         boolean isRecursive = false; // will be set to true if we have already  
  222.                                         // seen this object  
  223.         if (!isPrimitive) {  
  224.             if (m_visited.containsKey(obj))  
  225.                 isRecursive = true;  
  226.             m_visited.put(obj, true);  
  227.         }  
  228.   
  229.         final Class type = (fld == null || (obj != null && !isPrimitive)) ? obj  
  230.                 .getClass() : fld.getType();  
  231.         int arraySize = 0;  
  232.         int baseOffset = 0;  
  233.         int indexScale = 0;  
  234.         if (type.isArray() && obj != null) {  
  235.             baseOffset = unsafe.arrayBaseOffset(type);  
  236.             indexScale = unsafe.arrayIndexScale(type);  
  237.             arraySize = baseOffset + indexScale * Array.getLength(obj);  
  238.         }  
  239.   
  240.         final ObjectInfo root;  
  241.         if (fld == null) {  
  242.             root = new ObjectInfo("", type.getCanonicalName(), getContents(obj,  
  243.                     type), 0, getShallowSize(type), arraySize, baseOffset,  
  244.                     indexScale);  
  245.         } else {  
  246.             final int offset = (int) unsafe.objectFieldOffset(fld);  
  247.             root = new ObjectInfo(fld.getName(), type.getCanonicalName(),  
  248.                     getContents(obj, type), offset, getShallowSize(type),  
  249.                     arraySize, baseOffset, indexScale);  
  250.         }  
  251.   
  252.         if (!isRecursive && obj != null) {  
  253.             if (isObjectArray(type)) {  
  254.                 // introspect object arrays  
  255.                 final Object[] ar = (Object[]) obj;  
  256.                 for (final Object item : ar)  
  257.                     if (item != null)  
  258.                         root.addChild(introspect(item, null));  
  259.             } else {  
  260.                 for (final Field field : getAllFields(type)) {  
  261.                     if ((field.getModifiers() & Modifier.STATIC) != 0) {  
  262.                         continue;  
  263.                     }  
  264.                     field.setAccessible(true);  
  265.                     root.addChild(introspect(field.get(obj), field));  
  266.                 }  
  267.             }  
  268.         }  
  269.   
  270.         root.sort(); // sort by offset  
  271.         return root;  
  272.     }  
  273.   
  274.     // get all fields for this class, including all superclasses fields  
  275.     private static List<Field> getAllFields(final Class type) {  
  276.         if (type.isPrimitive())  
  277.             return Collections.emptyList();  
  278.         Class cur = type;  
  279.         final List<Field> res = new ArrayList<Field>(10);  
  280.         while (true) {  
  281.             Collections.addAll(res, cur.getDeclaredFields());  
  282.             if (cur == Object.class)  
  283.                 break;  
  284.             cur = cur.getSuperclass();  
  285.         }  
  286.         return res;  
  287.     }  
  288.   
  289.     // check if it is an array of objects. I suspect there must be a more  
  290.     // API-friendly way to make this check.  
  291.     private static boolean isObjectArray(final Class type) {  
  292.         if (!type.isArray())  
  293.             return false;  
  294.         if (type == byte[].class || type == boolean[].class  
  295.                 || type == char[].class || type == short[].class  
  296.                 || type == int[].class || type == long[].class  
  297.                 || type == float[].class || type == double[].class)  
  298.             return false;  
  299.         return true;  
  300.     }  
  301.   
  302.     // advanced toString logic  
  303.     private static String getContents(final Object val, final Class type) {  
  304.         if (val == null)  
  305.             return "null";  
  306.         if (type.isArray()) {  
  307.             if (type == byte[].class)  
  308.                 return Arrays.toString((byte[]) val);  
  309.             else if (type == boolean[].class)  
  310.                 return Arrays.toString((boolean[]) val);  
  311.             else if (type == char[].class)  
  312.                 return Arrays.toString((char[]) val);  
  313.             else if (type == short[].class)  
  314.                 return Arrays.toString((short[]) val);  
  315.             else if (type == int[].class)  
  316.                 return Arrays.toString((int[]) val);  
  317.             else if (type == long[].class)  
  318.                 return Arrays.toString((long[]) val);  
  319.             else if (type == float[].class)  
  320.                 return Arrays.toString((float[]) val);  
  321.             else if (type == double[].class)  
  322.                 return Arrays.toString((double[]) val);  
  323.             else  
  324.                 return Arrays.toString((Object[]) val);  
  325.         }  
  326.         return val.toString();  
  327.     }  
  328.   
  329.     // obtain a shallow size of a field of given class (primitive or object  
  330.     // reference size)  
  331.     private static int getShallowSize(final Class type) {  
  332.         if (type.isPrimitive()) {  
  333.             final Integer res = primitiveSizes.get(type);  
  334.             return res != null ? res : 0;  
  335.         } else  
  336.             return objectRefSize;  
  337.     }  
  338. }  

先一个测试类来验证一下Unsafe的方式计算出的结果

[html]  
 
  1. public class ClassIntrospectorTest  
  2. {  
  3.     public static void main(String[] args) throws IllegalAccessException {  
  4.         final ClassIntrospector ci = new ClassIntrospector();  
  5.   
  6.         ObjectInfo res;  
  7.           
  8.         res = ci.introspect( new ObjectA() );  
  9.         System.out.println( res.getDeepSize() );  
  10.     }  
  11.    
  12.     private static class ObjectA {  
  13.         String str;  // 4  
  14.         int i1; // 4  
  15.         byte b1; // 1  
  16.         byte b2; // 1  
  17.         int i2;  // 4   
  18.         ObjectB obj; //4  
  19.         byte b3;  // 1  
  20.     }  
  21.       
  22.     private static class ObjectB {  
  23.           
  24.     }  
  25. }  


计算结果如下:

32

和我们之前计算结果是一致的,证明是正确的。

最后再来测试一下数组对象的长度。有两个类如下:

[java]  
 
  1. private static class ObjectC {  
  2.         ObjectD[] array = new ObjectD[2];  
  3.     }  
  4.       
  5.     private static class ObjectD {  
  6.         int value;  
  7.     }  

它们在内存的大体分布如下图:

我们可以手工计算一下ObjectC obj = new ObjectC()的大小:

ObjectC的Shallow size = 8(_mark) + 4(oop指针)  + 4(ObjectD[]引用) = 16

new ObjectD[2]数组的长度 =  8(_mark) + 4(oop指针) + 4(数组长度占4个字节) + 4(ObjectD[0]引用) + 4(ObjectD[1]引用) = 24

由于ObjectD[]数组没有指向具体的对象大小,所以我们手工计算的结果是16 + 24 = 40

使用Unsafe对象的方式来计算一下:

[java]  
 
  1. public static void main(String[] args) throws IllegalAccessException {  
  2.         final ClassIntrospector ci = new ClassIntrospector();  
  3.   
  4.         ObjectInfo res;  
  5.           
  6.         res = ci.introspect( new ObjectC() );  
  7.         System.out.println( res.getDeepSize() );  
  8.     }  


计算结果如下,和我们计算的结果是一致的,证明是正确的:

40

再给ObjectD[]数组指向具体的ObjectD对象,再测试一下结果:

[java]  
 
  1. public static void main(String[] args) throws IllegalAccessException {  
  2.        final ClassIntrospector ci = new ClassIntrospector();  
  3.   
  4.        ObjectInfo res;  
  5.          
  6.        res = ci.introspect( new ObjectC() );  
  7.        System.out.println( res.getDeepSize() );  
  8.    }  
  9.      
  10.    private static class ObjectC {  
  11.     ObjectD[] array = new ObjectD[2];  
  12.       
  13.     public ObjectC(){  
  14.         array[0] = new ObjectD();  
  15.         array[1] = new ObjectD();  
  16.     }  
  17.    }  
  18.      
  19.    private static class ObjectD {  
  20.     int value;  
  21.    }  


我们可以手工计算一下ObjectC obj = new ObjectC()的大小:

ObjectC的Shallow size = 8(_mark) + 4(oop指针)  + 4(ObjectD[]引用) = 16

new ObjectD[2]数组的长度 =  8(_mark) + 4(oop指针) + 4(数组长度占4个字节) + 4(ObjectD[0]引用) + 4(ObjectD[1]引用) = 24

ObjectD对象长度 = 8(_mark) + 4(oop指针) + 4(value) = 16

所以ObjectC实际占用的空间 = 16 + 24 + 2 * 16 = 72

使用Unsafe的方式计算的结果也是72,和我们手工计算的方式一致。

原文地址:https://www.cnblogs.com/sea520/p/13182334.html