Understanding objects in Java

I'm trying to understand about objects in Java and how they reside in memory. I'm experimenting with the following application:

private static final Unsafe U = getUnsafe();

public static void main( String[] args )
{
    offsets(Test.class);
}

private static <T> void offsets(Class<T> clazz){
    Arrays.stream(clazz.getFields())
       .forEach(f -> 
            System.out.println(f.getName() + " offset:" + U.objectFieldOffset(f)
       )
    );
}

public static class Test{
    public boolean b;
    public byte b1;
    public short b2;
    public int b3;
}

The output:

b offset:18
b1 offset:19
b2 offset:16
b3 offset:12

QUESTION 1: I experimented with many kind of object and was surprised that fields offsets never less then 12. What is that 12? Some reserved object metadat?

QUESTION 2: Moreover I thought that memory alignement of the data structure should be equal to 4 or 8 bytes. But why offset of b1 is 19, for instance? How to interpret this Unsafe::fieldOffset output?

P.S. This is for educational purpose only, not intended for using in production.

Upvotes: 2

Views: 61

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198103

"Some reserved object metadata?" Yes.

"memory alignement of the data structure should be equal to 4 or 8 bytes." For the object as a whole, yes, but not necessarily for individual fields.

Upvotes: 4

Related Questions