主要思路 就是先獲取當前佔用內存(usedMemory) 而後建立對象 再獲取當前佔用內存 兩次內存差就是該對象所佔內存大小 runGC()方法提供垃圾回收在每次獲取內存前能夠先調用 對象
private static final Runtime s_runtime = Runtime.getRuntime();內存
private static void runGC() throws Exception {
// It helps to call Runtime.gc()// using several method calls:
for (int r = 0; r < 4; ++r)
_runGC();
}
private static void _runGC() throws Exception {
long usedMem1 = usedMemory(), usedMem2 = Long.MAX_VALUE;
for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++i) {
s_runtime.runFinalization();
s_runtime.gc();
Thread.currentThread().yield();
usedMem2 = usedMem1;
usedMem1 = usedMemory();
}
}
private static long usedMemory() {
return s_runtime.totalMemory() - s_runtime.freeMemory();
}
get