`
liuxinglanyue
  • 浏览: 562409 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

计算Java对象占用内存空间的大小(对于32位虚拟机而言)

    博客分类:
  • JVM
阅读更多

参考文档:http://liuxinglanyue.iteye.com/blog/855907

http://www.developersky.net/thread-97-1-1.html

 

Sizeof.java

 

package com.liuxinglanyue;

public class Sizeof
{
    public static void runGC () throws Exception
    {
        for (int r = 0; r < 4; ++ r) 
        	_runGC ();
    }
    public 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 ();
        }
    }
    public static long usedMemory ()
    {
        return s_runtime.totalMemory () - s_runtime.freeMemory ();
    }
    public static final Runtime s_runtime = Runtime.getRuntime ();
}

 Lang.java

 

package com.liuxinglanyue;

public class Lang 
{
	public static void main(String []args) throws Exception
	{
		Sizeof.runGC ();
		Sizeof.usedMemory ();
		long heap1 = Sizeof.usedMemory ();
		Te te = new Te();
		Sizeof.runGC();
		long heap2 = Sizeof.usedMemory();
		int size = Math.round ((float)(heap2 - heap1));
		System.out.println ("'before' heap: " + heap1 + ", 'after' heap: " + heap2);
		System.out.println ("heap delta: " + (heap2 - heap1));
		System.out.println("size = " + size + " bytes");
	}
}
class Te 
{
	int i;
//	boolean flag;
//	Object obj;
	Integer k;
}

 运行结果:

 

'before' heap: 137456, 'after' heap: 137472
heap delta: 16
size = 16 bytes
分享到:
评论
1 楼 liuxinglanyue 2014-12-02  
四年后的自己

这种方法 不靠谱。

使用javaagent的方式。
推荐两个工具 jol 、 Classmexer

相关推荐

Global site tag (gtag.js) - Google Analytics