首页 > 技术文章 > Java对象大小计算

shown 2016-12-22 14:40 原文

这篇说说如何计算Java对象大小的方法。之前在聊聊高并发(四)Java对象的表示模型和运行时内存表示 这篇中已经说了Java对象的内存表示模型是Oop-Klass模型。

普通对象的结构如下,按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] view plain copy
 
  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] view plain copy
 
  1. Premain-Class: sizeof.ObjectShallowSize  


打成jar包

 

 

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


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

 

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

 

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

 

 

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

 

[html] view plain copy
 
  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] view plain copy
 
  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] view plain copy
 
  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] view plain copy
 
  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://segmentfault.com/a/1190000004574249

 

推荐阅读