I have a question about Singleton objects and their initialization in a particular case.
I have a singleton class that has to be configured by providing a parameter through an init(...)
method that depends from a value in a configuration file at the startup of the application and that will never
change for the entire lifetime of the application. What I have to do in case of getInstance() method
invocation before that the init method has been called? Throw an exception? Which one? Or what?
If you want to throw an exception in that case, then look through the ones defined in the java.lang package and choose one which looks suitable. Make sure you distinguish between checked and unchecked exceptions when making your choice.
Joined: Oct 13, 2010
Thanks for your answers.
The object cannot be made usable before getting the initialization parameter.
The initialization value will be a factory class instance that will be used by the singleton instance object to produce an object
used in all its public methods.
For what concerns throwing an exception I was thinking about IllegalStateException but it is unchecked and if possible I
prefer to throw a checked exception...
thanks for your help but my scenario is a bit more complex; here it is:
Consider 3 threads that can execute concurrently the following and that the name of the Factory class "org.baltico.FactoryImpl" is known only
at runtime (taken from configuration file or something else)
Thread1 : new Object0.doSomething("org.baltico.FactoryImpl");
Thread2 : new Object1.doSomething();
Thread3 : new Object2.doSomething();
Michele Dibenedetto wrote:Maybe there is a bug in my design?
I would say that allowing other code to use your singleton object before it has been properly initialized might well qualify as a bug in your design. You should try to ensure this doesn't happen.
Joined: Apr 16, 2008
Michele, if the program requirements involve "concurrent" computation then the Simpleton design pattern is not appropriate. Simpleton is for simple things and a good academic exercise. In real-world enterprise computing, Simpleton implementations should be avoided.
Aside, Simpleton is easy for computer science professors to understand and easy for students to understand. However, it is a compensation for old-style procedural/sequential programming and not a true "object"-oriented design pattern. Unfortunately, computer science graduates come fresh out the gate ready to code a Singleton unaware of its limitations and associated problems, e.g. your design bug is rooted in trying to implement Singleton.