Sunday, October 16, 2005

What's a Singleton?

What's a Singleton? A commonly asked question. A Singleton is a class for which only one instance can exist within a program ie. only one single object of that particular class can be created in a program.

Write a class in a way which prevents a casual programmer from creating more than one instance. Have a constructor, but make it private so that no other classes may call it. Now that we have no constructor, we need to make a way for people to create a single instance of the class. Typically this is done by provding a static method which creates an instance, but will create only one. If it is called again, it just returns the same instance that it created the first time.

The last thing to remember is that Java is a multi-threaded language in which many things can be happening "at once". If two threads were to call getInstance at the same time, then our class might occasionally create two instances, which would be wrong and very hard to test. So we make use of Java's built-in synchronization mechanism to make sure that only one thread can call getInstance at any one time.

Here's the code:
public class SimpleSingleton
{
private static SimpleSingleton instance = null;

private SimpleSingleton() {}

public synchronized static SimpleSingleton getInstance()
{
if (instance == null)
{
instance = new SimpleSingleton();
}
return instance;
}

public void callMethod()
{
System.out.println("Calling it's method");
}

public static void main(String[] args)
{
SimpleSingleton.getInstance().callMethod();
}
}
Thanks to JavaRanch for the tip.

Technorati Tags: ,
Blogs linking to this article

1 Comments:

Blogger Vikram Shitole said...

We Can also Change the code some what to remove null checking every time we give call to getInstance.

by adding this to code
static {
instance = new SimpleSingleton();
}
This will initialize the object when it is loaded into the JVM.
and also no need to make the method getInstance syncronized.

9:16 PM  

Post a Comment

<< Home