Assume that there is an instance variable 'x' of type singleton class 'A' within the JVM. Now at later point of time within the same application I would like to get the instance 'x' assigned to the other variable 'z' of type class 'A'. How is it possible other than the "static get method defined to create a new instance of 'A' in the class 'A'. More specifically, is there any way by means of 'ClassLoader' or 'getClass()'.
Or, any way we can find out all instances of a given singleton or any class in JVM at runtime and can assign one particular instance thus received to other field variable.
One more thing is one of my singleton class data is not being updated by multiple classes on WINDOWS NT and throwing 'NullPointerException' while accessing the data for updation, where as the same code in UNIX box, data of the singleton class is being updated by multiple classes.
Don Yantzi, one of the Java/WebSphere developers and instructors crafted this answer...Dave
The intent of the Singleton design pattern as outlined in Design Patterns (Gamma, Helm, Johnson and Vlissides) is to "ensure a class only has one instance, and provide a global point of access to it." If you need to change the value of the singleton to a new instance throughout the course of your application you may want to rethink if a Singleton is the best approach.
Since the constructor for a Singleton is either protected or private, there is no other way to create an instance of the class other than from within the class itself. Calling x.getClass().newInstance() is equivalent to new A( ) and will result in a runtime exception (new A( ) will result in a compile time error.) That said, there is nothing stopping you from adding a new method to the Singleton class that creates a new instance of itself and assigns the new instance to the field 'x' (such as createNew() ), however, this does not strictly enforce the Singleton pattern since another class may be holding a reference to the previous instance not the new instance.
In response to your Windows NT versus Unix problem, first make sure that both environments are using a single JVM. The Singleton Class will only be unique within a single JVM (two JVM's will not share the same instance.) Also, if you are performing updates from multiple classes there may be threading and timing issues that will be different across hardware platforms. Make sure that updates are synchronized where appropriate and the order of updates is controlled if necessary.
Dig deeper on Web Development
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.