Reputation: 142
I started diving deeper in JVM, memory management and how objects are stored. So far I know that when a new object is created Object a = new Object()
a
is stored in the stack memory and holds a reference (location in heap memory) to the Object itself.
That's all good. But I'm wondering where the address to the reference is stored. How is this reference accessed? My assumption is that "a" holds the address to the first byte where the reference is located and since it's an object reference let's say that it will be 8 bytes long.
Here is a visual of what I imagine it's happening
I would appreciate If somebody can give me a more detailed explanation or a correct one if I'm wrong or point me to an article about it.
Now that I'm trying to explain it more question come up like: How do you know the object size? Is that stored somewhere in the object headers?
Upvotes: 1
Views: 2672
Reputation: 4348
Objects, apart from special circumstances like escape analysis, are allocated on the heap.
When you create a reference to another object it can be assigned to a local variable (stored on the stack) or instance/class field in which case it's stored inside the object holding the reference.
The reference points to some location on the heap and is automatically dereferenced by the Java runtime. From pure Java, you don't have access to raw pointers or an easy way how to check object's size.
The actual data/structure that is stored on the heap starts with what's commonly called object header. The header contains a (compressed) class pointer leading to the internal data structure defining layout of the class (stored in a separate memory area called Metaspace - or Compressed Class space if Compressed OOPs are used)
The pointer can be 4 or 8 bytes, depending on the architecture - even on 64-bit systems, it's usually 4 bytes due to the Comprosssed OOPs optimalization.
You can use jol tool to print object layout.
Finally, this post from Alexei Shipilev contains a lot more details about Java object layout: https://shipilev.net/jvm/objects-inside-out/
Upvotes: 2