static initialization order java

The static initializer for a class gets run when the class is loaded. The class is first loaded when you first access it, either to create an instance, or to access a static method or field.

So, for multiple classes, this totally depends on the code that’s run to cause those classes to get loaded.

1. static initilizer block of super class
2. static initilizer block of child class.
3. instance initilizer of super class.
4. rest of the super class constructor
5. instance initilizer of child class.
6. rest of the child class constructor.


Java static initializers are thread safe .

However, if you want to ensure that the code is executed exactly once you need to make sure that the class is only loaded by a single class-loader. Static initialization is performed once per class-loader.

class FooRegistry {     static { 

//this code must only ever be called once. Do not have to add synchronized block like:synchronized(FooRegistry.class)

        addController(new FooControllerImpl());     }    

 private static void addController(IFooController controller) {  
       // ...    

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s