Java Singleton classes
What is Singleton Class?
Singleton is a java object, which is restricted to a single instance. You would wonder what?
Java Object, which is restricted to a single instance. Yes you read this correct. The restriction is that Object can be created for a Singleton class but at any point you would only have a single Object for a Singleton class in Java Virtual Machine (JVM) to prevent developers creating duplicate copies.
Why would you want to create a Singleton Class? and What’s the use?
For example you would want have a system configuration in an Object available throughout your system in which case you would create a Singleton class to hold information (Only one instance – accessible globally in your application, No need to multiple copies of it if you could make this available in your system globally).
Creating an object wherever required and using it is a very bad practice and there are chances that some part of your application would be referring to old system configuration.
Now, Let’s take a look how to create a Singleton Classes. First Let’s see how java objects are created.
How Java Object’s created?
We all know that we instantiate or create a java object using the keyword ‘new’.
for e.g.,
MyNewClass myobj = new MyNewClass(); //This will invoke the default constructor
MyNewClass myobj = new MyNewClass ( param1,param2);// This will invoke the argument constructor defined in the MyNewClass
Now, the question arises that how do we prevent creating a multiple objects for the class MyNewClass
How to create a Singleton Objects?
Answer is simple,
When you don’t specify a parameter while creating an object, it uses a default constructor (when you define it in the class or not, it generates one during compile time). Now make your default constructor private as shown below
public class MyNewClass <br/>
{<br/>
private MyNewClass()</br>
{ </br>
//Code……No No..nothing required to be coded here. Will explain later
}
}
This will prevent creating an object (instane) of MyNewClass.
How do we get hold of Singleton classes?
In “How to create a Singleton Objects?” section, we have learnt how to prevent creating objects of the class. Now we should provide a mechanism to create one & only instance, keep it somewhere centrally and should provide a common method to access this single instance. Now Let’s write a code for MyNewClass to achieve this
Please follow my comments in the below (which explains everything that you need to know about Singleton class)
<pre>
public class MyNewClass
{
//Step1. Make class default constructor as private
private MyNewClass () //Prevents creating instances
{
// Actually no need to write any code here, keeping this with private //accessor makes this class Singleton
}
// Stpe2. Define a static method to access a singleton object (single instance)
public static MyNewClass getMyNewClass()
{
//Now how do you give a user single instance of this class. Hmm You need a //variable to hold this. Let’s define a class member variable and make sure its //private ( refer to step 3)
if ( mynewObjRef == null ) // Oh null, seems to be a first call. Let’s create an object.
{
mynewObjRef = new MyNewClass (); // This is fine as private constructor is //accessible
}
}
//Step3. Define a class member variable to hold the instance
private static MyNewClass mynewObjRef = null;
}
</pre>
That’s it. Now you have created a Singleton class. This is beautiful and gets your job done having a single instance throughout your application. Now you could do all sorts of stuff with your singleton class having more methods and stuff defined it to access it wherever needed in your application.
Avoid Threads cutting your Singleton class head
I mean how do we avoid thread issues with Singleton class. I’m being funny, please ignore or just have a laugh good for your health. Now let’s come to the business
What thread problems with Singleton classes?
Image a scenario where multiple threads accessing the getMyNewClass() method at the same time. It would possibly return two instances for thread A and B. You do want that not to happen. Do you? If you do, then you don’t need a Singleton class ☺
To prevent this, you need to add a keyword ‘synchronized’ to your method.
Changed method declaration:
public static synchronized MyNewClass getMyNewClass()
That’s it. You’re done !!!
Oh HANG ON……… Developers are too brainier; they know how to make duplicate copies of an Object
How developers create Duplicate Copies of an Object?
Developers weapon is a ‘clone()’ method on an Object. That’s their weapon. This is what I write (I’m a developer too) to create duplicate objects.
<pre>
public class DevClass
{
public static void main( String args[] )
{
//This will give us a singleton class instance (object)
MyNewClass obj = MyNewClass.getMyNewClass();
//Here is the cracker, cloning an object ( creating a duplicate)
MyNewClass dup = (MyNewClass) obj.clone();
}
</pre>
OK. Now you have learnt how to clone an object.
You can’t do anything to clone method as it comes for all classes as gift. I mean all classes by default extends java.lang.Object.
The only option I could think of is to override this method in your MyNewClass like below to restrict cloning.
Here you go, our final version of MyNewClass
<pre>
public class MyNewClass
{
//Step1. Make class default constructor as private
private MyNewClass () //Prevents creating instances
{
// Actually no need to write any code here, keeping this with private //accessor makes this class Singleton
}
// Stpe2. Define a static method to access a singleton object (single instance)
public static MyNewClass getMyNewClass()
{
//Now how do you give a user single instance of this class. Hmm You need a //variable to hold this. Let’s define a class member variable and make sure its //private ( refer to step 3)
if ( mynewObjRef == null ) // Oh null, seems to be a first call. Let’s create an object.
{
mynewObjRef = new MyNewClass (); // This is fine as private constructor is //accessible
}
}
//Step3. Define a class member variable to hold the instance
private static MyNewClass mynewObjRef = null;
//Prevent Cloning, just throw an exception to inform the user
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
</pre>
Now I guess you have learnt about Java Singleton Classes.
Do what you love! But To be a Techy, do more reading
