Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Steps in the memory allocation process for Java objects

What happens in the memory when a class instantiates the following object?

public class SomeObject{

    private String strSomeProperty;

    public SomeObject(String strSomeProperty){
        this.strSomeProperty = strSomeProperty;
    }
    public void setSomeProperty(String strSomeProperty){
        this.strSomeProperty = strSomeProperty;
    }
    public String getSomeProperty(){
        return this.strSomeProperty;
    }
}

In class SomeClass1:

SomeObject so1 = new SomeObject("some property value");

In class SomeClass2:

SomeObject so2 = new SomeObject("another property value");

How is memory allocated to the newly instantiated object and its properties?

like image 251
Sajal Dutta Avatar asked Nov 26 '08 14:11

Sajal Dutta


1 Answers

Let's step through it:

SomeObject so1 = new SomeObject("some property value");

... is actually more complicated than it looks, because you're creating a new String. It might be easier to think of as:

String tmp = new String("some property value");
SomeObject so1 = new SomeObject(tmp);
// Not that you would normally write it in this way.

(To be absolutely accurate - these are not really equivalent. In the original the 'new String' is created at compile time and is part of the .class image. You can think of this as a performance hack.)

So, first the JVM allocates space for the String. You typically don't know or care about the internals of the String implementation, so just take it on trust that a chunk of memory is being used to represent "some property value". Also, you have some memory temporarily allocated containing a reference to the String. In the second form, it's explicitly called tmp; in your original form Java handles it without naming it.

Next the JVM allocates space for a new SomeObject. That's a bit of space for Java's internal bookkeeping, and space for each of the object's fields. In this case, there's just one field, strSomeProperty.

Bear in mind that strSomeProperty is just a reference to a String. For now, it'll be initialised to null.

Next, the constructor is executed.

this.strSomeProperty = strSomeProperty;

All this does is copy the reference to the String, into your strSomeProperty field.

Finally, space is allocated for the object reference so1. This is set with a reference to the SomeObject.

so2 works in exactly the same way.

like image 132
slim Avatar answered Oct 21 '22 03:10

slim