views:

3668

answers:

6

This question is for the java language in particular. I understand that there is a static protion of memory set aside for all static code.

My question is how is this static memory filled? Is a static object put into static memory at import, or at first reference? Also, do the same garbage collection rules apply to static objects as they do for all other objects?


public class Example{
    public static SomeObject someO = new SomeObject();
}
/********************************/
// Is the static object put into static memory at this point?
import somepackage.Example;

public class MainApp{
    public static void main( Sting args[] ){
// Or is the static object put into memory at first reference?
       Example.someO.someMethod();
// Do the same garbage collection rules apply to a 
//     static object as they do all others?
       Example.someO = null;
       System.gc();
    }
}
+2  A: 

There is normally no such thing as "static" memory. Most vm's have the permanent generation of the heap (where classes get loaded), which is normally not garbage collected.

Static objects are allocated just like any other object. But, if they live for long they will be moved between the different generations in the garbage collector. But they will not end up in permgenspace.

If your class is holding onto this object permanently, it will only be released when the vm exits.

krosenvold
+3  A: 

This static variable some0 is initialized as soon as your class is referenced in your code. In your example this will be executed in first line of your main method.

You can validate this by creating a static initializer block. Put a break point in this initializer block and you'll see, when it will be called. Or even more simplier... put a breakpoint in the constructor of SomeObject.

Yaba
+3  A: 

The initialization of static variables is covered in Section 2.11 Static Initializers of suns JVM spec. The specification does not define the implementation of Garbage collection however so I imagine that garbage collection rules for static objects will vary depending on your VM.

Kevin Loney
+11  A: 
erickson
+2  A: 

It should be noted, that only the pointer (or any other primitive type) is stored in the PermGenSpace (thats the proper name for the area where the static stuff is stored).

So the Object referenced by the pointer sits in the normal heap, like any other object.

Thomas Morgner
A: 

If the static field is changed to reference a different object, the original object pointed to by the static field is eligible for GC just like any other object.

It could also be free'ed (even if not nulled) if the class itself is unloaded and the entire object graph is cut from the heap. Of course, when a class can be unloaded is a good topic for a host of other questions... :)

Alex Miller