I have an interesting question on initialization. I have the following code:
public class ErrorLookupProvider {
private static final ErrorLookupProvider INSTANCE = new ErrorLookupProvider();
private static Map<Long, List<String>> map = new HashMap<Long, List<String>>();
private ErrorLookupProvider() {
init();
}
private void init() {
map.put(123L, ImmutableList.of("abc", "def"));
}
public static ErrorLookupProvider getInstance() {
return INSTANCE;
}
}
Now when I call ErrorLookupProvider.getInstance(), I hit an NPE. The map inside init() is not initialized with the new HashMap.
If I change the declaration of map to be final, then I see that it is initialized. Or, even if I remove static and make it a private class variable as private Map<.....> that works too.
I haven't been able to figure out why this happens. Can someone explain what is happening here?