java如何獲取一個對象的大小
When---什麽時候需要知道對象的內存大小
在內存足夠用的情況下我們是不需要考慮java中一個對象所占內存大小的。但當一個系統的內存有限,或者某塊程序代碼允許使用的內存大小有限制,又或者設計一個緩存機制,當存儲對象內存超過固定值之後寫入磁盤做持久化等等,總之我們希望像寫C一樣,java也能有方法實現獲取對象占用內存的大小。
How---java怎樣獲取對象所占內存大小
在回答這個問題之前,我們需要先了解java的基礎數據類型所占內存大小。
數據類型 | 所占空間(byte) |
byte | 1 |
short | 2 |
int | 4 |
long | 8 |
float | 4 |
double | 8 |
char | 2 |
boolean | 1 |
當然,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獲取對象所占內存大小的方法:
假設我們有一個類的定義如下:
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} 10 11 private static class ObjectB { 12 13 }
如果我們直接按照上面掌握的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 包中定義的一個接口,也是這個包的核心部分,集中了其中幾乎所有的功能方法,例如類定義的轉換和操作等。
1 package instrumentation.test; 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 }
2. 在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包,並通過代碼測試對象所占內存大小:
1 System.out.println(ObjectShallowSize.sizeOf(new ObjectA())); // 32
5. 在運行調用ObjectShallowSize.sizeof的類的工程中加上剛打的jar包依賴,同時eclipse裏面run configuration,在VM arguments中添加(標紅部分為jar包的決定路徑):
-javaagent:E:/software/instrumentation-sizeof.jar
方式2---使用Unsafe來獲取
關於Unsafe的使用,後面我會專門開一個專題來詳細講述,這裏暫時讓我們來見識下Unsafe的神奇之處。
1 private final static Unsafe UNSAFE; 2 // 只能通過反射獲取Unsafe對象的實例 3 static { 4 try { 5 UNSAFE = (Unsafe) Unsafe.class.getDeclaredField("theUnsafe").get(null); 6 } catch (Exception e) { 7 throw new Error(); 8 } 9 } 10 11 Field[] fields = ObjectA.class.getDeclaredFields(); 12 for (Field field : fields) { 13 System.out.println(field.getName() + "---offSet:" + UNSAFE.objectFieldOffset(field)); 14 }
輸出結果為:
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---深入分析的一個例子:
以下代碼摘抄自原鏈接:
1 package test; 2 3 import java.lang.reflect.Array; 4 import java.lang.reflect.Field; 5 import java.lang.reflect.Modifier; 6 import java.util.ArrayList; 7 import java.util.Arrays; 8 import java.util.Collections; 9 import java.util.HashMap; 10 import java.util.IdentityHashMap; 11 import java.util.List; 12 import java.util.Map; 13 14 import sun.misc.Unsafe; 15 16 public class ClassIntrospector { 17 18 private static final Unsafe unsafe; 19 /** Size of any Object reference */ 20 private static final int objectRefSize; 21 static { 22 try { 23 Field field = Unsafe.class.getDeclaredField("theUnsafe"); 24 field.setAccessible(true); 25 unsafe = (Unsafe) field.get(null); 26 27 // 可以通過Object[]數組得到oop指針究竟是壓縮後的4個字節還是未壓縮的8個字節 28 objectRefSize = unsafe.arrayIndexScale(Object[].class); 29 } catch (Exception e) { 30 throw new RuntimeException(e); 31 } 32 } 33 34 /** Sizes of all primitive values */ 35 private static final Map<Class<?>, Integer> primitiveSizes; 36 37 static { 38 primitiveSizes = new HashMap<Class<?>, Integer>(10); 39 primitiveSizes.put(byte.class, 1); 40 primitiveSizes.put(char.class, 2); 41 primitiveSizes.put(int.class, 4); 42 primitiveSizes.put(long.class, 8); 43 primitiveSizes.put(float.class, 4); 44 primitiveSizes.put(double.class, 8); 45 primitiveSizes.put(boolean.class, 1); 46 } 47 48 /** 49 * Get object information for any Java object. Do not pass primitives to 50 * this method because they will boxed and the information you will get will 51 * be related to a boxed version of your value. 52 * 53 * @param obj 54 * Object to introspect 55 * @return Object info 56 * @throws IllegalAccessException 57 */ 58 public ObjectInfo introspect(final Object obj) 59 throws IllegalAccessException { 60 try { 61 return introspect(obj, null); 62 } finally { // clean visited cache before returning in order to make 63 // this object reusable 64 m_visited.clear(); 65 } 66 } 67 68 // we need to keep track of already visited objects in order to support 69 // cycles in the object graphs 70 private IdentityHashMap<Object, Boolean> m_visited = new IdentityHashMap<Object, Boolean>( 71 100); 72 73 private ObjectInfo introspect(final Object obj, final Field fld) 74 throws IllegalAccessException { 75 // use Field type only if the field contains null. In this case we will 76 // at least know what‘s expected to be 77 // stored in this field. Otherwise, if a field has interface type, we 78 // won‘t see what‘s really stored in it. 79 // Besides, we should be careful about primitives, because they are 80 // passed as boxed values in this method 81 // (first arg is object) - for them we should still rely on the field 82 // type. 83 boolean isPrimitive = fld != null && fld.getType().isPrimitive(); 84 boolean isRecursive = false; // will be set to true if we have already 85 // seen this object 86 if (!isPrimitive) { 87 if (m_visited.containsKey(obj)) 88 isRecursive = true; 89 m_visited.put(obj, true); 90 } 91 92 final Class<?> type = (fld == null || (obj != null && !isPrimitive)) ? obj 93 .getClass() : fld.getType(); 94 int arraySize = 0; 95 int baseOffset = 0; 96 int indexScale = 0; 97 if (type.isArray() && obj != null) { 98 baseOffset = unsafe.arrayBaseOffset(type); 99 indexScale = unsafe.arrayIndexScale(type); 100 arraySize = baseOffset + indexScale * Array.getLength(obj); 101 } 102 103 final ObjectInfo root; 104 if (fld == null) { 105 root = new ObjectInfo("", type.getCanonicalName(), getContents(obj, 106 type), 0, getShallowSize(type), arraySize, baseOffset, 107 indexScale); 108 } else { 109 final int offset = (int) unsafe.objectFieldOffset(fld); 110 root = new ObjectInfo(fld.getName(), type.getCanonicalName(), 111 getContents(obj, type), offset, getShallowSize(type), 112 arraySize, baseOffset, indexScale); 113 } 114 115 if (!isRecursive && obj != null) { 116 if (isObjectArray(type)) { 117 // introspect object arrays 118 final Object[] ar = (Object[]) obj; 119 for (final Object item : ar) 120 if (item != null) 121 root.addChild(introspect(item, null)); 122 } else { 123 for (final Field field : getAllFields(type)) { 124 if ((field.getModifiers() & Modifier.STATIC) != 0) { 125 continue; 126 } 127 field.setAccessible(true); 128 root.addChild(introspect(field.get(obj), field)); 129 } 130 } 131 } 132 133 root.sort(); // sort by offset 134 return root; 135 } 136 137 // get all fields for this class, including all superclasses fields 138 private static List<Field> getAllFields(final Class<?> type) { 139 if (type.isPrimitive()) 140 return Collections.emptyList(); 141 Class<?> cur = type; 142 final List<Field> res = new ArrayList<Field>(10); 143 while (true) { 144 Collections.addAll(res, cur.getDeclaredFields()); 145 if (cur == Object.class) 146 break; 147 cur = cur.getSuperclass(); 148 } 149 return res; 150 } 151 152 // check if it is an array of objects. I suspect there must be a more 153 // API-friendly way to make this check. 154 private static boolean isObjectArray(final Class<?> type) { 155 if (!type.isArray()) 156 return false; 157 if (type == byte[].class || type == boolean[].class 158 || type == char[].class || type == short[].class 159 || type == int[].class || type == long[].class 160 || type == float[].class || type == double[].class) 161 return false; 162 return true; 163 } 164 165 // advanced toString logic 166 private static String getContents(final Object val, final Class<?> type) { 167 if (val == null) 168 return "null"; 169 if (type.isArray()) { 170 if (type == byte[].class) 171 return Arrays.toString((byte[]) val); 172 else if (type == boolean[].class) 173 return Arrays.toString((boolean[]) val); 174 else if (type == char[].class) 175 return Arrays.toString((char[]) val); 176 else if (type == short[].class) 177 return Arrays.toString((short[]) val); 178 else if (type == int[].class) 179 return Arrays.toString((int[]) val); 180 else if (type == long[].class) 181 return Arrays.toString((long[]) val); 182 else if (type == float[].class) 183 return Arrays.toString((float[]) val); 184 else if (type == double[].class) 185 return Arrays.toString((double[]) val); 186 else 187 return Arrays.toString((Object[]) val); 188 } 189 return val.toString(); 190 } 191 192 // obtain a shallow size of a field of given class (primitive or object 193 // reference size) 194 private static int getShallowSize(final Class<?> type) { 195 if (type.isPrimitive()) { 196 final Integer res = primitiveSizes.get(type); 197 return res != null ? res : 0; 198 } else 199 return objectRefSize; 200 } 201 }
下面來分析ObjectC所占內存大小:
1 package test; 2 3 public class IntrospectorTest { 4 private static class ObjectC { 5 ObjectD[] array = new ObjectD[2]; 6 } 7 8 private static class ObjectD { 9 int value; 10 } 11 12 public static void main(String[] args) throws IllegalAccessException { 13 final ClassIntrospector ci = new ClassIntrospector(); 14 ObjectInfo res = ci.introspect(new ObjectC()); 15 System.out.println( res.getDeepSize() ); 16 } 17 }
代碼輸出為: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
java如何獲取一個對象的大小