When---什么时候需要知道对象的内存大小
在内存足够用的情况下我们是不需要考虑java中一个对象所占内存大小的。但当一个系统的内存有限,或者某块程序代码允许使用的内存大小有限制,又或者设计一个缓存机制,当存储对象内存超过固定值之后写入磁盘做持久化等等,总之我们希望像写C一样,java也能有方法实现获取对象占用内存的大小。

How---java怎样获取对象所占内存大小
在回答这个问题之前,我们需要先了解java的基础数据类型所占内存大小。

数据类型所占空间(byte)
byte    1
short2
int4
long8
float4
double8
char  2
boolean1

当然,java作为一种面向对象的语言,更多的情况需要考虑对象的内存布局,java对于对象所占内存大小需要分两种情况考虑:

对象类型内存布局构成
一般非数组对象8个字节对象头(mark) + 4/8字节对象指针 + 数据区 + padding内存对齐(按照8的倍数对齐)
数组对象8个字节对象头(mark) + 4/8字节对象指针 + 4字节数组长度 + 数据区 + padding内存对齐(按照8的倍数对齐)

可以看到数组类型对象和普通对象的区别仅在于4字节数组长度的存储区间。而对象指针究竟是4字节还是8字节要看是否开启指针压缩。Oracle JDK从6 update 23开始在64位系统上会默认开启压缩指针
http://rednaxelafx.iteye.com/blog/1010079。如果要强行关闭指针压缩使用-XX:-UseCompressedOops,强行启用指针压缩使用: -XX:+UseCompressedOops。接下来我们来举例来看实现java获取对象所占内存大小的方法:假设我们有一个类的定义如下:

     private static class ObjectA {  
         String str;   // 4  
         int i1;       // 4  
         byte b1;      // 1  
         byte b2;      // 1  
         int i2;       // 4   
         ObjectB obj;  //4  
         byte b3;      // 1  
     }  
 
     private static class ObjectB {  
         
     }

如果我们直接按照上面掌握的java对象内存布局进行计算,则有:

Size(ObjectA) = Size(对象头(_mark)) + size(oop指针) + size(数据区)
Size(ObjectA) = 8 + 4 + 4(String) + 4(int) + 1(byte) + 1(byte) + 2(padding) + 4(int) + 4(ObjectB指针) + 1(byte) + 7(padding)
Size(ObjectA) = 40

我们直接通过两种获取java对象内存占用大小的方式来验证我们的计算是否正确。

方式1---通过Instrumentation来获取
这种方法得到的是Shallow Size,即遇到引用时,只计算引用的长度,不计算所引用的对象的实际大小。如果要计算所引用对象的实际大小,必须通过递归的方式去计算。
查看jdk的代码发现,Instrumentation是一个接口,本来我想的是可以直接定义一个类实现该接口。但是看了下该接口里面的方法瞬间傻眼。根本没法去重写。
calm down,原来Instrumentation接口的实例需要使用代理的方式来获得。具体步骤如下:

  1. 编写 premain 函数
    编写一个 Java 类,包含如下两个方法当中的任何一个
    public static void premain(String agentArgs, Instrumentation inst); [1]
    public static void premain(String agentArgs); [2]
    其中,[1] 的优先级比 [2] 高,将会被优先执行([1] 和 [2] 同时存在时,[2] 被忽略)。
    在这个 premain 函数中,开发者可以进行对类的各种操作。
    agentArgs 是 premain 函数得到的程序参数,随同 “– javaagent”一起传入。与 main 函数不同的是,这个参数是一个字符串而不是一个字符串数组,如果程序参数有多个,程序将自行解析这个字符串。
    Inst 是一个 java.lang.instrument.Instrumentation 的实例,由 JVM 自动传入。java.lang.instrument.Instrumentation 是 instrument 包中定义的一个接口,也是这个包的核心部分,集中了其中几乎所有的功能方法,例如类定义的转换和操作等。
 package instrumentation.test;
 
 import java.lang.instrument.Instrumentation;
 
 public class ObjectShallowSize {
     private static Instrumentation inst;  
 
     public static void premain(String agentArgs, Instrumentation instP){  
         inst = instP;  
     }  
 
     public static long sizeOf(Object obj){  
         return inst.getObjectSize(obj);  
     }  
 }
  1. 在META-INF下面新建MANIFEST.MF文件,并且指定
    Manifest-Version: 1.0
    Premain-Class: instrumentation.test.ObjectShallowSize
    3.通过eclipse->export->jar->next->next,然后选中定制的 MANIFEST.MF 文件,进行jar打包。4. 给需要使用ObjectShallowSize的工程引入该jar包,并通过代码测试对象所占内存大小:
    1System.out.println(ObjectShallowSize.sizeOf(newObjectA()));//32
  2. 在运行调用ObjectShallowSize.sizeof的类的工程中加上刚打的jar包依赖,同时eclipse里面run configuration,在VM arguments中添加(标红部分为jar包的绝对路径):
    -javaagent:E:/software/instrumentation-sizeof.jar

方式2---使用Unsafe来获取
关于Unsafe的使用,后面我会专门开一个专题来详细讲述,这里暂时让我们来见识下Unsafe的神奇之处。

     private final static Unsafe UNSAFE;
     // 只能通过反射获取Unsafe对象的实例
     static {
         try {
             UNSAFE = (Unsafe) Unsafe.class.getDeclaredField("theUnsafe").get(null);
         } catch (Exception e) {
             throw new Error();
         }
     }
 
     Field[] fields = ObjectA.class.getDeclaredFields();
     for (Field field : fields) {
       System.out.println(field.getName() + "---offSet:" + UNSAFE.objectFieldOffset(field));
     }

输出结果为:

str---offSet:24
i1---offSet:12
b1---offSet:20
b2---offSet:21
i2---offSet:16
obj---offSet:28
b3---offSet:22

我们同样可以算得对象实际占用的内存大小:

Size(ObjectA) = Size(对象头(_mark)) + size(oop指针) + size(排序后数据区) = 8 + 4 + (28+4-12) = 32.

我们再回过头来,看我们在通过代码获取对象所占内存大小之前的预估值40。比我们实际算出来的值多了8个字节。通过Unsafe打印的详细信息,我们不难想到这其实是由hotspot创建对象时的排序决定的:

HotSpot创建的对象的字段会先按照给定顺序排列,默认的顺序为:从长到短排列,引用排最后: long/double –> int/float –> short/char –> byte/boolean –> Reference。

所以我们重新计算对象所占内存大小得:

Size(ObjectA) = Size(对象头(_mark)) + size(oop指针) + size(排序后数据区)
Size(ObjectA) = 8 + 4 + 4(int) + 4(int) + byte(1) + byte(1) + 2(padding) + 4(String) + 4(ObjectB指针)
Size(ObjectA) = 32

与上面计算结果一致。

Deeper---深入分析的一个例子:
以下代码摘抄自原链接:

 package test;
 
 import java.lang.reflect.Array;
 import java.lang.reflect.Field;
 import java.lang.reflect.Modifier;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.IdentityHashMap;
 import java.util.List;
 import java.util.Map;
 
 import sun.misc.Unsafe;
 
 public class ClassIntrospector {
 
     private static final Unsafe unsafe;  
     /** Size of any Object reference */  
     private static final int objectRefSize;  
     static {  
         try {  
             Field field = Unsafe.class.getDeclaredField("theUnsafe");  
             field.setAccessible(true);  
             unsafe = (Unsafe) field.get(null);  
 
             // 可以通过Object[]数组得到oop指针究竟是压缩后的4个字节还是未压缩的8个字节
             objectRefSize = unsafe.arrayIndexScale(Object[].class);  
         } catch (Exception e) {  
             throw new RuntimeException(e);  
         }  
     }  
 
     /** Sizes of all primitive values */  
     private static final Map<Class<?>, Integer> primitiveSizes;  
 
     static {  
         primitiveSizes = new HashMap<Class<?>, Integer>(10);  
         primitiveSizes.put(byte.class, 1);  
         primitiveSizes.put(char.class, 2);  
         primitiveSizes.put(int.class, 4);  
         primitiveSizes.put(long.class, 8);  
         primitiveSizes.put(float.class, 4);  
         primitiveSizes.put(double.class, 8);  
         primitiveSizes.put(boolean.class, 1);  
     }  
 
     /** 
      * Get object information for any Java object. Do not pass primitives to 
      * this method because they will boxed and the information you will get will 
      * be related to a boxed version of your value. 
      *  
      * @param obj 
      *            Object to introspect 
      * @return Object info 
      * @throws IllegalAccessException 
      */  
     public ObjectInfo introspect(final Object obj)  
             throws IllegalAccessException {  
         try {  
             return introspect(obj, null);  
         } finally { // clean visited cache before returning in order to make  
                     // this object reusable  
             m_visited.clear();  
         }  
     }  
 
     // we need to keep track of already visited objects in order to support  
     // cycles in the object graphs  
     private IdentityHashMap<Object, Boolean> m_visited = new IdentityHashMap<Object, Boolean>(  
             100);  
 
     private ObjectInfo introspect(final Object obj, final Field fld)  
             throws IllegalAccessException {  
         // use Field type only if the field contains null. In this case we will  
         // at least know what's expected to be  
         // stored in this field. Otherwise, if a field has interface type, we  
         // won't see what's really stored in it.  
         // Besides, we should be careful about primitives, because they are  
         // passed as boxed values in this method  
         // (first arg is object) - for them we should still rely on the field  
         // type.  
         boolean isPrimitive = fld != null &amp;&amp; fld.getType().isPrimitive();  
         boolean isRecursive = false; // will be set to true if we have already  
                                         // seen this object  
         if (!isPrimitive) {  
             if (m_visited.containsKey(obj))  
                 isRecursive = true;  
             m_visited.put(obj, true);  
         }  
 
         final Class<?> type = (fld == null || (obj != null &amp;&amp; !isPrimitive)) ? obj  
                 .getClass() : fld.getType();  
         int arraySize = 0;  
         int baseOffset = 0;  
         int indexScale = 0;  
         if (type.isArray() &amp;&amp; obj != null) {  
             baseOffset = unsafe.arrayBaseOffset(type);  
             indexScale = unsafe.arrayIndexScale(type);  
             arraySize = baseOffset + indexScale * Array.getLength(obj);  
         }  
 
         final ObjectInfo root;  
         if (fld == null) {  
             root = new ObjectInfo("", type.getCanonicalName(), getContents(obj,  
                     type), 0, getShallowSize(type), arraySize, baseOffset,  
                     indexScale);  
         } else {  
             final int offset = (int) unsafe.objectFieldOffset(fld);  
             root = new ObjectInfo(fld.getName(), type.getCanonicalName(),  
                     getContents(obj, type), offset, getShallowSize(type),  
                     arraySize, baseOffset, indexScale);  
         }  
 
         if (!isRecursive &amp;&amp; obj != null) {  
             if (isObjectArray(type)) {  
                 // introspect object arrays  
                 final Object[] ar = (Object[]) obj;  
                 for (final Object item : ar)  
                     if (item != null)  
                         root.addChild(introspect(item, null));  
             } else {  
                 for (final Field field : getAllFields(type)) {  
                     if ((field.getModifiers() &amp; Modifier.STATIC) != 0) {  
                         continue;  
                     }  
                     field.setAccessible(true);  
                     root.addChild(introspect(field.get(obj), field));  
                 }  
             }  
         }  
 
         root.sort(); // sort by offset  
         return root;  
     }  
 
     // get all fields for this class, including all superclasses fields  
     private static List<Field> getAllFields(final Class<?> type) {  
         if (type.isPrimitive())  
             return Collections.emptyList();  
         Class<?> cur = type;  
         final List<Field> res = new ArrayList<Field>(10);  
         while (true) {  
             Collections.addAll(res, cur.getDeclaredFields());  
             if (cur == Object.class)  
                 break;  
             cur = cur.getSuperclass();  
         }  
         return res;  
     }  
 
     // check if it is an array of objects. I suspect there must be a more  
     // API-friendly way to make this check.  
     private static boolean isObjectArray(final Class<?> type) {  
         if (!type.isArray())  
             return false;  
         if (type == byte[].class || type == boolean[].class  
                 || type == char[].class || type == short[].class  
                 || type == int[].class || type == long[].class  
                 || type == float[].class || type == double[].class)  
             return false;  
         return true;  
     }  
 
     // advanced toString logic  
     private static String getContents(final Object val, final Class<?> type) {  
         if (val == null)  
             return "null";  
         if (type.isArray()) {  
             if (type == byte[].class)  
                 return Arrays.toString((byte[]) val);  
             else if (type == boolean[].class)  
                 return Arrays.toString((boolean[]) val);  
             else if (type == char[].class)  
                 return Arrays.toString((char[]) val);  
             else if (type == short[].class)  
                 return Arrays.toString((short[]) val);  
             else if (type == int[].class)  
                 return Arrays.toString((int[]) val);  
             else if (type == long[].class)  
                 return Arrays.toString((long[]) val);  
             else if (type == float[].class)  
                 return Arrays.toString((float[]) val);  
             else if (type == double[].class)  
                 return Arrays.toString((double[]) val);  
             else  
                 return Arrays.toString((Object[]) val);  
         }  
         return val.toString();  
     }  
 
     // obtain a shallow size of a field of given class (primitive or object  
     // reference size)  
     private static int getShallowSize(final Class<?> type) {  
         if (type.isPrimitive()) {  
             final Integer res = primitiveSizes.get(type);  
             return res != null ? res : 0;  
         } else  
             return objectRefSize;  
     }  
 }

下面来分析ObjectC所占内存大小:

 package test;
 
 public class IntrospectorTest {
     private static class ObjectC {  
         ObjectD[] array = new ObjectD[2];  
     }  
 
     private static class ObjectD {  
         int value;  
     }  
     
     public static void main(String[] args) throws IllegalAccessException {
         final ClassIntrospector ci = new ClassIntrospector();  
         ObjectInfo res = ci.introspect(new ObjectC());  
         System.out.println( res.getDeepSize() );  
     }
 }

代码输出为:40。

下面我们来分析下ObjectC的内存布局:

ShallowSize(ObjectC) = Size(对象头) + Size(oop指针) + Size(内容) + Size(对齐)

ShallowSize(ObjectC) = 8 + 4 + 4(ObjectD[]数组引用) =16

Size(ObjectD[] arr) = 8(数组对象头) + 4(oop指针) + 4(数组长度) + 4(ObjectD[0]对象引用) + 4(ObjectD[1]对象引用) = 24

因为arr没有具体赋值,所以此时具体引用的为null,不占用内存。否则需要再次计算ObjectD的内存最后想加。

所以总共得到:Size(ObjectC) = ShallowSize(ObjectC) + Size(ObjectD[] arr) = 40。

参考链接:
http://blog.csdn.net/antony9118/article/details/54317637
https://www.cnblogs.com/licheng/p/6576644.html