tags:

views:

100

answers:

2
+2  Q: 

java memory usage

I know I always post a similar question about array memory usage but now I want post the question more specific.

After I read this article: http://www.javamex.com/tutorials/memory/object_memory_usage.shtml

I didn't understand some things:

  • the size of a data type is always the same also on different platform (Linux / Windows 32 / 64 bit)??? so an int will be always 32 bit?;
  • when I compute the memory usage I must put also the reference value itself? If I have an object to a class that has an int field its memory will be 12 (object header) + 4 reference + 4 (the int field) + 3 (padding) = 24 bytes??
+1  A: 

Firstly, yes, an int will always be 32 bits, as per the language specification.

You shouldn't (IMO) include the reference itself in memory usage for the class itself, because it's not part of the object. In particular, you don't know how many places there will be references to the same object: if 10 different objects each store a reference to your object, you'll end up paying the reference cost 10 times. However, you should take account of the reference when computing the cost of whatever is storing it - so if you have a class with a field which is a reference, then count the cost there instead. (Likewise if you're computing stack space, consider local variables.)

Jon Skeet
I don't think the JLS specifies an exact bit size anywhere. The specified value range only means that an `int` needs to be **at least** 32bit wide. Nothing in the JLS or JVM spec specifies that an `int` must use only 4 bytes in memory.
Joachim Sauer
@Joachim: True - and due to field alignment it could end up taking up more even if only 4 bytes are used. However, it's worth being aware that at least at a *language* level it's a 4-byte value. It will *always* wrap around at 2^31 etc.
Jon Skeet
+1  A: 

An int will always be 32 bits. However, the JVM spec does not mandate that the fields of an object are stored contiguously in memory. So it is possible that a 64 bit JVM might align int fields on 64 bit boundaries. (Certainly, Sun 32 bit JVM's align 8 and 16 bit fields on 32 bit boundaries!)

Stephen C
so can we say that every JVM implementation can choose that extra spaces?
xdevel2000
No we cannot say that. Or at least, we cannot without testing each and every one of them. (And that is impossible, because people are free to create their own private variants, based on the OpenJDK code-base for example.)
Stephen C