Thursday, January 26, 2012

Java static initialization gotcha

If you have a class which has a singleton instance of itself as a static member, and also use a static inititialization block, then you can run into an issue with initialization like I did where static final members are null.
01 import java.util.*;
02
03 class MySingletonClass {
04 private static final instance = new MySingletonClass();
05 private static final List MY_STRINGS;
06 static {
07 MY_STRINGS = new ArrayList();
08 }
09 public MySingletonClass() {
10 System.out.println("MY_STRINGS: "+MYSTRINGS);
11 }
12 }

The above will throw a NullPointer Exception on line 10 because the MySingletonClass constructor is called BEFORE the static initialization block is executed. So change it to this:
01 import java.util.*;
02
03 class MySingletonClass {
04 private static final instance;
05 private static final List MY_STRINGS;
06 static {
07 MY_STRINGS = new ArrayList();
08 instance = new MySingletonClass();
09 }
10 public MySingletonClass() {
11 System.out.println("MY_STRINGS: "+MYSTRINGS);
12 }
13 }

Now the instance static member variable is not created until AFTER the other static member is initialized. So the constructor can correctly execute the print statement.

No comments:

About Me

My photo
Lead Java Developer Husband and Father

Tags