Wednesday, May 1, 2013

Life Cycle of an Object in Java

In Java, objects play the pivotal role; so understanding its instantiation, and how and when it gets garbage collected is important. This post covers the life cycle of objects inside Java Virtual Machine. But keep in mind that, successful creation of the object is possible only if class is already loaded in JVM (by class loader).

Object Creation 

Class instantiation activity gives life to an object and thereafter you can call its methods to manipulate states/attributes. Object creation is done by Java Virtual Machine(after class has been loaded). When JVM creates a new instance of a class, it allocates memory on the heap to hold the object's instance. Memory is allocated for all variables/attributes declared in object's class and in all its superclasses (including hidden attributes). Once the virtual machine has allocated memory for the new object, the machine initializes the instance variable to default initial values. After this VM gives proper initial value depending on how the object gets created:

   1.  new keyword
        Person p = new Person();
        String s = new String("life");
            This is one of the most frequently used approach to create an instance of a class. 

       2.  newInstance() on a Class / Reflection
            Class class = Class.forName("");
            Object obj = class.newInstance();
            Person p = (Person)obj;

       3. Cloning         
           Person pClone = (Person)p.clone(); 

           Make sure that, Person class implements Cloneable interface and also provides the definition of the clone() method. 

       4. Deserialization      
           FileInputStream fis = new FileInputStream("person.ser");
           ObjectInputStream ois = new ObjectInputStream(fis);
           Person per =(Person)ois.readObject(); 
           Deserialization is a technique to convert the encoded byte stream into the corresponding object as 
           shown above. Refer to the detailed tutorial.

       5. Implicit Instantiation
           All above techniques explicitly creates an object of a class. Apart from above, there are multiple implicit ways of object creation as well :
           1. Class loading : For every type that a JVM loads, it implicitly creates a new Class object to                  represent that type.
           2. String Literals : When JVM loads a class which has String literals (i.e. String PI = "3.14"), 
               it might create a new String object. 
           3. Expression Evaluation : Process of evaluation an expression like String concatenation
               can also create new objects. 
     So above explicit/implicit object instantiation techniques give proper initial value to the object. JVM uses one of the three techniques to do this task, depending on how the object is being created.

    If the object is being created because of a clone() invocation, the virtual machine copies the values of the instance variables of the object being cloned into the new object. If the object is deserialized via a readObject() invocation on an ObjectInputStream, the virtual machine initializes non-transient instance object variables from values read from the input stream. Otherwise, the virtual machine invokes an instance initialization method on the object. The instance initialization method initializes the object's instance variables to their proper initial value. 
    The Java compiler generates at least one instance initialization method for every class it compiles. In the  Java class file, the instance initialization method is called "<init>". For each constructor in the source code of a class, the Java compiler generates one <init>() method.  

    Object in action

    Once object is created successfully, its ready for the real action.

    Garbage Collection of Object / End of life

    Application can allocate memory for object via explicit and implicit ways described under object creation, but they can not explicitly free that memory. To signal to JVM that an object is ready for garbage collection, object needs to get unrefrenced in either of below ways :

    1. Explicit unreferencing
        person = null;  //person is an instance of Person   

    2. Object goes out of scope
        An Object created inside a method goes out of scope once method returns to the calling method.
        So in below case once method() is over, p implicitly becomes null. 

        public void method(){
           Person p = new Person();
           //method action

       After unrefrencing, VM can reclaim that memory. Virtual machine can decide when to garbage collect unrefrenced object. But specification doesn't guarantee any predictable behavior. It is up-to the VM to decide when to reclaim memory from unrefrenced object or it might NOT reclaim memory at all.
    If the class declares a finalizer (i.e. public void finalize() method ) then Garbage Collector will execute the finalize() method on the instance of the class before it frees the memory space occupied by that instance. So clearly, exact time of garbage collection is unpredictable.

    No comments:

    Post a Comment