Andy Malakov software blog

Thursday, October 8, 2009

sizeof and object padding in Java

Consider the following classes:

class Struct1 {
byte b1;

class Struct2 extends Struct1 {
byte b2;

class Struct3 extends Struct2 {
byte b3;

class Struct4 extends Struct3 {
byte b4;

class Struct5 extends Struct4 {
byte b5;

class Struct6 extends Struct5 {
byte b6;

class Struct7 extends Struct6 {
byte b7;

class Struct8 extends Struct7 {
byte b8;

class FlatStruct8 {
byte b1, b2, b3, b4, b5, b6, b7, b8;

On my JVM (1.6.0_16 64-bit):

sizeof (new Struct8()) = 80 (sic!)
sizeof (new FlatStruct8()) = 24

Now, 24 makes sense (8 bytes of data + 2 x 8 bytes of object overhead). In case of Struct8, we can see that Java pads fields declared in each class to so that total block size will be multiple of 8.

I used both Instrumentation-based and GC-based sizeof () implementations to confirm this.

On 32-bit JVM (1.6.0_04-b12) blocks are padded to multiple of 4.

sizeof (new Struct8()) = 40
sizeof (new FlatStruct8()) = 24

More about padding.