2

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.

1 Answer 1

4

"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.

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to estimate the alignment of Test in that case?
Btw, very interesting... Why is the offset of b field 18? Even if it put as the first one?
Could you advise some tool for monitoring object layout (with all metadata)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.