Thursday, February 17, 2011

Object Life Cycle in Java


 An object typically goes through most of the following states between the time it is allocated and the time its resources are finally returned to the system for reuse.

  1. Created
  2. In use (strongly reachable)
  3. Invisible
  4. Unreachable
  5. Collected
  6. Finalized
  7. Deallocated
Lets understand these in detail :

1 Created

When an object is created, several things occur:
  1. Space is allocated for the object.
  2. Object construction begins.
  3. The superclass constructor is called.
  4. Instance initializers and instance variable initializers are run.
  5. The rest of constructor body is executed.
The exact costs of these operations depend on the implementation of the JVM, as well as the implementation of the class being constructed. The thing to keep in mind is that these costs exist. Once the object has been created, assuming it is assigned to some variable, it moves directly to the in use state.

2 In Use

Objects that are held by at least one strong reference are considered to be in use. In JDK 1.1.x, all references are strong references. Java 2 introduces three other kinds of references: weak, soft and phantom. and assigns it to some variables.
public class CatTest {
        static Vector catList = new Vector();
        static void makeCat() {
                Object cat = new Cat();
                catList.addElement(cat);
        }
        
        public static void main(String[] arg) {
                makeCat();
                // do more stuff
        }
}

Creating and referencing an object
Fig. shows the structure of the objects inside the VM just before the makeCat method returns. At that moment, two strong references point to the Cat object.
Object reference graph

When the makeCat method returns, the stack frame for that method and any temporary variables it declares are removed. This leaves the Cat object with just a single reference from the catList static variable (indirectly via the Vector).

3 Invisible

An object is in the invisible state when there are no longer any strong references that are accessible to the program, even though there might still be references. Not all objects go through this state, and it has been a source of confusion for some developers.Listing  shows a code fragment that creates an invisible object.
public void run() {
    try {
        Object foo = new Object();
        foo.doSomething();
    } catch (Exception e) {
        // whatever
    }
    while (true) { // do stuff } // loop forever
}

Invisible object
In this example, the object foo falls out of scope when the try block finishes. It might seem that the foo temporary reference variable would be pulled off the stack at this point and the associated object would become unreachable. After all, once the try block finishes, there is no syntax defined that would allow the program to access the object again. However, an efficient implementation of the JVM is unlikely to zero the reference when it goes out of scope. The object referenced by foo continues to be strongly referenced, at least until the run method returns. In this case, that might not happen for a long time. Because invisible objects can't be collected, this is a possible cause of memory leaks. If you run into this situation, you might have to explicitly null your references to enable garbage collection.

4 Unreachable

An object enters an unreachable state when no more strong references to it exist. When an object is unreachable, it is a candidate for collection. Note the wording: Just because an object is a candidate for collection doesn't mean it will be immediately collected. The JVM is free to delay collection until there is an immediate need for the memory being consumed by the object.
It's important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. GC roots are a special class of variable that includes
  • Temporary variables on the stack (of any thread)
  • Static variables (from any class)
  • Special references from JNI native code
Circular strong references don't necessarily cause memory leaks. Consider the code in Listing A-3. It creates two objects, and assigns them references to each other.
public void buidDog() {
   Dog newDog = new Dog();
   Tail newTail = new Tail();
   newDog.tail = newTail;
   newTail.dog = newDog;
}

Circular reference
Figure below shows the reference graph for the objects before the buildDog method returns. Before the method returns, there are strong references from the temporary stack variables in the buildDog method pointing to both the Dog and the Tail.
Reference graph before buildDog returns




Figure below shows the graph for the objects after the buildDog method returns. At this point, the Dog and Tail both become unreachable from a root and are candidates for collection (although the VM might not actually collect these objects for an indefinite amount of time).

Reference graph after buildDog returns


5 Collected

An object is in the collected state when the garbage collector has recognized an object as unreachable and readies it for final processing as a precursor to deallocation. If the object has a finalize method, then it is marked for finalization. If it does not have a finalizer then it moves straight to the finalized state.
If a class defines a finalizer, then any instance of that class must have the finalizer called prior to deallocation. This means that deallocation is delayed by the inclusion of a finalizer.

.6 Finalized

An object is in the finalized state if it is still unreachable after its finalize method, if any, has been run. A finalized object is awaiting deallocation. Note that the VM implementation controls when the finalizer is run. The only thing that can be said for certain is that adding a finalizer will extend the lifetime of an object. This means that adding finalizers to objects that you intend to be short-lived is a bad idea. You are almost always better off doing your own cleanup instead of relying on a finalizer. Using a finalizer can also leave behind critical resources that won't be recovered for an indeterminate amount of time. If you are considering using a finalizer to ensure that important resources are freed in a timely manner, you might want to reconsider.
One case where a finalize method delayed GC was discovered by the quality assurance (QA) team working on Swing. The QA team created a stress testing application that simulated user input by using a thread to send artificial events to the GUI. Running on one version of the toolkit, the application reported an OutOfMemoryError after just a few minutes of testing. The problem was finally traced back to the fact that the thread sending the events was running at a higher priority than the finalizer thread. The program ran out of memory because about 10,000 Graphics objects were held in the finalizer queue waiting for a chance to run their finalizers. It turned out that these Graphics objects were holding onto fairly substantial native resources. The problem was fixed by assuring that whenever Swing is done with a Graphics object, dispose is called to ensure that the native resources are freed as soon as possible.
In addition to lengthening object lifetimes, finalize methods can increase object size. For example, some JVMs, such as the classic JVM implementation, add an extra hidden field to objects with finalize methods so that they can be held in a linked list finalization queue.

7 Deallocated

The deallocated state is the final step in garbage collection. If an object is still unreachable after all the above work has occurred, then it is a candidate for deallocation. Again, when and how deallocation occurs is up to the JVM.

No comments:

Post a Comment

subversion video