Wednesday, 24 May 2017

Java program to create singleton class

Java Singleton design pattern is one of the design patterns that manages the instantiation of an object
This design pattern suggests that only one instance of a Singleton object is created by the JVM.
This pattern is useful when exactly one object is needed to coordinate actions across the system.

For example, you can use it to create a connection pool. It’s not good to create a new connection every time a program needs to write something to a database; instead, a connection
or a set of connections that are already a pool can be instantiated using the Singleton pattern.

Example Class that follows Singleton Pattern.

public class SingletonExample {  
   private static SingletonExample INSTANCE = new SingletonExample ();  
   //Marking default constructor private;  
   //to avoid direct instantiation.  
   private SingletonExample () {  
   //Get instance for class SingletonExample  
   public static SingletonExample getInstance() {  
    return INSTANCE;  

In above code snippet, we have declared a static object reference to SingletonExample class called INSTANCE and is returned every time getInstance() is called.

  • In in a multi-threaded environment ,sometimes when two or more threads enter the method getInstance() at the same time before Singleton instance is not created, will result into simultaneous creation of two objects.

Such problems can be avoided by defining getInstance() method synchronized.

public static synchronized SingletonExample getInstance() { }  

Enjoy Learning.

No comments:

Post a Comment