I was re-factoring an open-source project for fun.
I found file backed configuration classes which are singleton in nature
and they were implemented in a look-like-singleton way
i decided to convert them all into Singleton.
Since it doesn’t need synchronization and
those configuration files needed at start-up not subject to lazy initialization
I preferred static final member and private constructor solution.
class Singleton{
private Singleton(){
...
}
private final Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
class had a member named doc which is initialized inside a method init()
this method is called by constructor.
...
private Document doc;
private Singleton(){
init();
}
private void init(){
doc = ....
}
Code seemed okay but was failing “magically”,
Singleton.getInstance().getDocument() was giving a null doc instance.
After some digging,
I realized that code inside the constructor was just ignored,
Debugger didn’t care break points
whether inside constructor or init() too.
Even throwing a RuntimeException inside constructor had no effect.
i searched about that issue
only found some information about tomcat and jboss may fail in that situation :
http://www.c2.com/cgi/wiki?JavaSingleton
This last approach seems to work well in most cases — and perhaps it is supposed to work per the Java spec. But — as I’ve recently learned the hard way — both Tomcat and JBoss do not always execute this code correctly. In particular, if some code is placed in the body of the constructor, even something trivial like logging to System.out, it is not always executed. I’ve also had initialization of member variables silently fail in the constructor. Unfortunately, deadlines have driven me to seek workarounds rather than research this situation. I’d love to learn more about it, even if that means learning I’ve made some big dumb mistake in what I was trying!
doesn’t give the reason (at least i am not alone.)
NOTE : The code i was working on was swt-powered desktop application ( although tomcat’s servlet-api.jar was in my classpath ).
It’s obviously a bug somewhere
but i can not dare to report it ( first i should isolate the part of code reproduces the issue ).
but if someone interested
i will give the road-map i was on
maybe you’ll see the monster too.