singleton implementation

来源:互联网 发布:淘宝买家信用等级v6 编辑:程序博客网 时间:2024/05/21 04:21


原文地址:http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-with-examples

Thread Safe Singleton:

           The easier way to create a thread-safe singleton class is to make the global access methodsynchronized,

so that only one thread can execute this method at a time. General implementation of this approach is like the below class

ThreadSafeSingleton.java

















packagecom.journaldev.singleton;
 
publicclass ThreadSafeSingleton {
 
    privatestatic ThreadSafeSingleton instance;
     
    privateThreadSafeSingleton(){}
     
    publicstatic synchronizedThreadSafeSingleton getInstance(){
        if(instance ==null){
            instance =new ThreadSafeSingleton()               
            returninstance;
    }
     }
     Above implementation works fine and provides thread-safety but it reduces the performance
becauseof cost associated with the synchronized method, although we need it only for the first few
threads who might create the separate instances (Read:Java Synchronization). To avoid this extra
overhead everytime, doublechecked locking principle is used. In this approach, the synchronized block
is used inside the if conditionwith an additional check to ensure that only one instance of singleton
class is created.

Below code snippet provides the double checked locking implementation.

public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
    if(instance ==null){
        synchronized(ThreadSafeSingleton.class) {
            if(instance ==null){
                instance =new ThreadSafeSingleton();
            }
        }
    }
    returninstance;
}

Bill Pugh Singleton Implementation:

  Prior to Java 5, java memory model had a lot of issues and above approaches used to fail in

certain scenarios where too many threads try to get the instance of the Singleton class simultaneously.

 So Bill Pugh came up with a different approach to create the Singleton class using a

 inner static helper class. The Bill Pugh Singleton implementation goes like this;

package com.journaldev.singleton;
 
public class BillPughSingleton {
 
    privateBillPughSingleton(){}
     
    privatestatic class SingletonHelper{
        privatestatic final BillPughSingleton INSTANCE = new BillPughSingleton();
    }
     
    publicstatic BillPughSingleton getInstance(){
        returnSingletonHelper.INSTANCE;
    }
}

    Notice the private inner static class that contains the instance of the singleton class.

When the singleton class is loaded, SingletonHelper class is not loaded into memory and only when

someone calls the getInstance method, this class gets loaded and creates the Singleton class instance.

This is the most widely used approach for Singleton class as it doesn’t require synchronization.

I am using this approach in many of my projects and it’s easy to understand and implement also.

Using Reflection to destroy Singleton Pattern

      Reflection can be used to destroy all the above singleton implementation approaches.

Let’s see this with an example class.

public class EagerInitializedSingleton {
     
    privatestatic final EagerInitializedSingleton instance = newEagerInitializedSingleton();
     
    //private constructor to avoid client applications to use constructor
    privateEagerInitializedSingleton(){}
 
    publicstatic EagerInitializedSingleton getInstance(){
        returninstance;
    }
}
public class ReflectionSingletonTest {
 
    publicstatic void main(String[] args) {
        EagerInitializedSingleton instanceOne = EagerInitializedSingleton.getInstance();
        EagerInitializedSingleton instanceTwo =null;
        try{
            Constructor[] constructors = EagerInitializedSingleton.class.getDeclaredConstructors();
            for(Constructor constructor : constructors) {
                //Below code will destroy the singleton pattern
                constructor.setAccessible(true);
                instanceTwo = (EagerInitializedSingleton) constructor.newInstance();
                break;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(instanceOne.hashCode());
        System.out.println(instanceTwo.hashCode());
    }
}
      If your singleton class is not using a lot of resources, this is the approach to use.
But in most of the scenarios, Singleton classes are created for resources such as File System,
Database connections etc and we should avoid the instantiation until unless client calls the
getInstance method. Also this method doesn’t provide any options for exception handling
0 0