0 Replies Latest reply: Dec 21, 2013 9:03 AM by DavidThi808 RSS

How does Java structure memory for an object's members?

DavidThi808 Newbie
Currently Being Moderated

I'm trying to figure out how Java structures/allocates memory for objects. (Yes this is implementation specific. I'm using the Oracle 1.7 runtime for this.) I did some work on this here and here and the results are confusing.

First off, in both referenced links, when I allocated an array of objects, the equivalent of new Object[10000], it used 4 bytes per object. On a 32-bit system this makes perfect sense. But I'm on a 64-bit system so what's going on here?

  1. Is Java limited to a 32-bit address space even on 64-bit systems?
  2. Is Java limited to a 32-bit address space per array and each array object then has a pointer to where the elements are?
  3. Something else?

Second, I compared the memory footprint of 8 booleans vs. a byte as the variables in a class. The 8 booleans requires 24 bytes/object or 3 bytes/boolean. The single byte approach requires 10 bytes/object.

  1. What is going on with 3 bytes/boolean? I would understand 4 (making each an int) and definitely 1 (making each a byte. But 3?
  2. And what's with expanding a byte to 10 bytes? I would understand 8 where it's expanding a byte to a native int (I'm on a 64-bit system). But what's with the other 2 bytes?

And in the case of different ways to create a RGB class it gets really weird.

  1. For a class composed of 3 byte variables it uses 24 bytes/instance. Expensive but understandable as each uses an int.
  2. So I tried where each class is a single int with the RGB stored in parts of the int (using bit shifting). And it's still 24 bytes/instance. Why on earth is Java taking 3 ints for storage? This makes no sense.
  3. But the weirdest case is where the class has a single variable of "byte[] color = new byte3;" Note that the byte is allocated so it's not just a null pointer. This approach takes less memory than the other two approaches. How???

Any guidance as to what is going on here is appreciated. I have a couple of classes that get allocated a lot and the flywheel pattern won't work (these objects have their values changed all over the place).

And an associated question, does the order of declaring variables matter? Back in the old days when I did C++ programming, declaring "int, byte, int, byte" used 4 int's work of space while "int, int, byte, byte" used 3.

thanks - dave


  • Correct Answers - 10 points
  • Helpful Answers - 5 points