How to Create a Singleton Object

This example shows how to create a singleton object. A singleton is a class of which there can only be one instance in the same Java Virtual Machine.
To create a singleton there has to be a private constructor because the class will itself control the one and only instance that will be created, and of course a private constructor cannot be called from outside the class.
Instead, a method is created with public access that returns the singleton instance (if the method is called the first time the object is instantiated). The example class MySingleton illustrates this:

Continue reading