Possible Duplicate:
In Java, what is the best way to determine the size of an object?
I found this piece of code on the net:
static Runtime runtime = Runtime.getRuntime();
...
long start, end;
Object obj;
runtime.gc();
start = runtime.freememory();
obj = new Object(); // Or whatever you want to look at
end = runtime.freememory();
System.out.println("That took " + (start-end) + "
bytes.");
But it is not very reliable, any idea on how to do it better?
The JVM allocates memory in chunks so it can be performed across threads concurrently. This called the Thread-Local Allocation Buffer.
If you turn this off with
-XX:-UseTLAByou will get more accurate memory usage information.prints with default options
0
0
0
0
0
0
0
0
0
0
with
-XX:-UseTLAB16
16
16
16
16
16
16
16
16
16