主要思路 就是先获取当前占用内存(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();
}
原文:http://www.cnblogs.com/IT-WJ/p/3610847.html