What do Java objects look like in memory during run-time?

As you may already know that once an object is created, it's just a series of bytes in the heap. You may be curious about how exactly Java objects look like in the memory?

1. Fields

Here is an example of an object layout for class "Base"(B). This class does not have any method. We will see how methods are laid out in memory later in the post.

If we have another class "Derived"(D) extending this "Base" class. The memory layout would look like the following:

Child object has the same memory layout as parent objects, except that it needs more space to place the newly added fields. The benefit of this layout is that a pointer of type B pointing at a D object still sees the B object at the beginning. Therefore, operations done on a D object through the B reference guaranteed to be safe, and there is no need to check what B points at dynamically.

2. Methods

Following the same logic, the method can be put at the beginning of the objects.

However, this approach is not efficient. If a class has many methods(e.g. M), then each object must have O(M) pointers set. In addition, each object needs to have space for O(M) pointers. Those make creating objects slower and objects bigger.

The optimization approach is to create a virtual function table (or vtable) which is an array of pointers to the member function implementations for a particular class. Create a single instance of the vtable for each class and make each object store a pointer to the vtable.

This is the optimized approach.

* The above are my notes for Standford compilers lectures which has very good animation.

References:
1. Stanford Compilers Lectures
2. JVM

Category >> Basics  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. liam on 2014-3-6

    Is the optimized approach being used now?

  2. avn te on 2014-6-22

    nice

  3. tapan on 2015-1-23

    nice article, where is object type information stored? Would it be in the frame stack

  4. a11ght on 2015-3-30

    nice article

  5. BogdanPaun on 2015-6-18

    Thanks for the article.
    “The benefit of this layout is that A pointer” – that should be a lower case A, not a capital, right?

  6. GOWRI SANKAR on 2016-2-7

    You’re right. I was wondering if there’s an entity with the name A.

  7. Aaron Chalker on 2017-8-28

    Was going smooth until I reached that “O(M)” thing, are you so much in a hurry you couldn’t give it a proper name?! What is this O(M) supposed to mean ?!

Leave a comment

*