Monday, September 09, 2013

Java Static Initializers

It's always interesting to explore other people's code and learn new constructs or see different ways of doing things. I was just looking at some code that uses static initializers in Java.  Personally I have never used this and wondered if there were any pros and cons to doing things this way.

The pros are that a static initializer will load something that is required by your class once and only once assuming your class was only loaded once over the life of your program. If a class is loaded and unloaded the static initializer will be called twice as noted in this article (and also if the class is loaded by multiple class loaders):

http://www2.sys-con.com/itsg/virtualcd/java/archives/0305/maso/index.html
 
With a static initializer you can throw an exception as well during instantiation of the class.

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

An example is in the code I am looking at which loads a resource for a program:

 static
    {
        try
        {
            ResourceBundle props= ResourceBundle.getBundle("/com/x/y");
            Enumeration<?> i = props.getKeys();
            while(i.hasMoreElements())
            {
                String prop = (String)i.nextElement();
                String m = props.getString(prop);
                map.put(prop,m);
            }
        }
        catch(MissingResourceException e)
        {
            //do some logging

        }
    } 

Another important point with static initializers is that the variable initialization code in the class will get executed in the order it is written. Therefore you need to have the static initializer before any code that would wipe it out, or use it.

More on static initializers from the Java Language Specification:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.7

As for the use of static variables in general...here are some interesting articles discouraging the use of static:

http://www.offthehill.org/articles/2011/06/03/java-static-variables-are-wrong-almost-always/

http://sensualjava.blogspot.com/2008/12/case-against-static-initializers.html

Statics make testing a nightmare:

http://www.jusfortechies.com/java/core-java/static-blocks.php

Static variables can break unit tests

http://erlend.oftedal.no/blog/?blogid=53

More problems with static variables:

http://gbracha.blogspot.com/2008/02/cutting-out-static.html

Do not use public non final static variables for security reasons:

https://www.securecoding.cert.org/confluence/display/java/OBJ10-J.+Do+not+use+public+static+nonfinal+variables

Global variables are bad

http://c2.com/cgi/wiki?GlobalVariablesAreBad

More notes on security and static variables (initialization to be specific):

http://www.securingjava.com/chapter-seven/chapter-seven-1.html