Latest web development tutorials

Singleton Pattern

Singleton (Singleton Pattern) Java is one of the simplest design pattern. This type of design patterns belong create schema, which provides the best way to create objects.

This model involves a single class that is responsible for creating your own objects, while ensuring that only a single object is created. This class provides a unique object of their visit, it can be accessed directly, you do not need to instantiate an object of that class.

note:

  • 1, singleton class can have only one instance.
  • 2, singleton class must create their own unique instance.
  • 3, singleton class must provide this example to all other objects.

Introduction

Intent: to ensure that only one instance of a class, and provide a global access point to access it.

The main solution: use a global class frequently created and destroyed.

When to use: When you want to control the number of instances when, to save system resources.

How to solve: determining whether the system already has this single case, if it returns, if not then created.

The key code: the constructor is private.

Application examples: 1, a party can only have one president.2, Windows is a multi-process, multi-threaded, in the operation of a file when it inevitably multiple processes or threads simultaneously a document of the phenomenon, the processing of all files must be performed by a unique instance. 3, some of the equipment manager is often designed as a single-case model, such as a computer with two printers in the output when necessary to deal with two printers can not print the same file.

Advantages: 1, only one instance in memory, reducing memory overhead, especially frequent create and destroy instances (such as School of Management Home page cache).2, to avoid multiple occupancy of resources (such as file write operations).

Cons: no interface, not inherit, and single responsibility principle conflict, a class should only be concerned about the internal logic, not on the outside like how to instantiate.

Usage scenarios: 1, require the production of a unique serial number.2, WEB counters, not every database in Riga once with a single case to refresh cached. 3, an object created by the need for excessive consumption of resources, such as I / O connection to the database and so on.

Note: getInstance () method requires the use of synchronization lock synchronized (Singleton.class) to prevent multiple threads into the cause instance is instantiated multiple times.

achieve

We will create aSingleObjectclass.SingleObjectclass has its own private constructor and a static instance.

SingleObjectclass provides a static method for obtaining outside its static instance.SingletonPatternDemo,our demonstration classes usingSingleObjectclass to getSingleObjectobject.

Singleton pattern UML diagram

step 1

Create a Singleton class.

SingleObject.java

public class SingleObject {

   // Create an object SingleObject private static SingleObject instance = new SingleObject ();

   // Make constructor private, so the class will not be instantiated private SingleObject () {}

   // Get the sole object of public available static SingleObject getInstance () {
      return instance;
   }

   public void showMessage () {
      System.out.println ( "Hello World!");
   }
}

Step 2

Get unique object from singleton class.

SingletonPatternDemo.java

public class SingletonPatternDemo {
   public static void main (String [] args) {

      // Constructor // illegal compile-time error: Constructor SingleObject () is not visible // SingleObject object = new SingleObject ();

      // Get the only object available SingleObject object = SingleObject.getInstance ();

      // Display message object.showMessage ();
   }
}

Step 3

Verify output.

Hello World!

Several Singleton pattern implementation

Implement singleton pattern a number of ways, as follows:

1, lazy style, thread-safe

Are Lazy initialization: Yes

Are multi-thread safe: No

Achieve Difficulty: Easy

Description: This method is the most basic way to achieve this implementation the biggest problem is not support multi-threading.Because there is no lock synchronized, so the strict sense it is not a singleton.
Lazy loading in this way obviously does not require thread safety, work in a multi-threaded does not work.

Code examples:

public class Singleton {  
    private static Singleton instance;  
    private Singleton () {}  
  
    public static Singleton getInstance () {  
    if (instance == null) {  
        instance = new Singleton ();  
    }  
    return instance;  
    }  
}  

The next presentation of several implementations support multiple threads, but differ in performance.

2, lazy style, thread-safe

Are Lazy initialization: Yes

Are multi-thread safe: Yes

Achieve Difficulty: Easy

Description: in this way have a good lazy loading, can work well in a multi-thread, however, is very low efficiency, 99% of cases does not require synchronization.
Advantage: The first call was initialized, to avoid wasted memory.
Cons: Must be locked synchronized to ensure a single case, but the lock will affect the efficiency.
getInstance () the performance of the application is not critical (which use less frequently).

Code examples:

public class Singleton {  
    private static Singleton instance;  
    private Singleton () {}  
    public static synchronized Singleton getInstance () {  
    if (instance == null) {  
        instance = new Singleton ();  
    }  
    return instance;  
    }  
} 

3, starving formula

Are Lazy Initialization: No

Are multi-thread safe: Yes

Achieve Difficulty: Easy

Description: It's more common, but prone to garbage objects.
Advantages: not locked, the efficiency is improved.
Disadvantages: class loader is initialized, memory is wasted.
It is based on classloder mechanism avoids synchronization multithreading, however, instance when it is instantiated class loader, although the cause class loading a variety of reasons, most of the Singleton pattern is to call the getInstance method, but it can not be determined there are other ways (or other static methods) leads to class loading, this time apparently did not reach instance initialization lazy loading effect.

Code examples:

public class Singleton {  
    private static Singleton instance = new Singleton ();  
    private Singleton () {}  
    public static Singleton getInstance () {  
    return instance;  
    }  
}  

4, double-check lock / double checking lock (DCL, that is double-checked locking)

JDK version: JDK1.5 from

Are Lazy initialization: Yes

Are multi-thread safe: Yes

Realize the difficulty: more complex

Description: This method uses double locking mechanism, safety and, in the case of multi-threading to maintain high performance.
getInstance () performance of applications is critical.

Code examples:

public class Singleton {  
    private volatile static Singleton singleton;  
    private Singleton () {}  
    public static Singleton getSingleton () {  
    if (singleton == null) {  
        synchronized (Singleton.class) {  
        if (singleton == null) {  
            singleton = new Singleton ();  
        }  
        }  
    }  
    return singleton;  
    }  
}  

5, registration type / static inner classes

Are Lazy initialization: Yes

Are multi-thread safe: Yes

Realize the difficulty: General

Description: This method can achieve the same effect double-check lock mode, but the implementation easier.Use lazy initialization of static field should be used in this way instead of double check the lock mode. This only applies to the case of a static field, double-check the lock mode can be used when needed delay to initialize instance fields.
This approach also takes advantage of classloder mechanisms to ensure that only one thread instance initialization, it is with 3 different ways is: as long as the third way Singleton class is loaded, the instance is instantiated (not reached lazy loading effect), but this approach is Singleton class is loaded, instance may not be initialized. Because SingletonHolder class is not actively used, only displayed through the call getInstance method, appears loaded SingletonHolder class, which is instantiated instance. Imagine, if you instantiate instance resource-intensive, so it wanted to delay loading, on the other hand, when you do not want to instantiate Singleton class loader, because it can not ensure Singleton class may also be active in other areas so as to be loaded, this time to instantiate instance clearly inappropriate. This time, in this way compared to the first three kinds of ways it is very reasonable.

Code examples:

public class Singleton {  
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton ();  
    }  
    private Singleton () {}  
    public static final Singleton getInstance () {  
    return SingletonHolder.INSTANCE;  
    }  
}   

6, enumerate

JDK version: JDK1.5 from

Are Lazy Initialization: No

Are multi-thread safe: Yes

Achieve Difficulty: Easy

Description: This implementation has not yet been widely adopted, but this is the best way to implement singleton pattern.It is more concise, automatic support serialization mechanism to prevent multiple instances of the absolute.
This approach is Effective Java author Josh Bloch advocates a way that it can not only avoid multi-thread synchronization problems, but also automatically supports serialization mechanism to prevent deserialization re-create a new object, absolutely prevent multiple instantiation. However, since only joined after JDK1.5 enum properties, write in this way can not help but feel strange, in practice, rarely used.
Not by reflection attack to call the private constructor.

Code examples:

public enum Singleton {  
    INSTANCE;  
    public void whateverMethod () {  
    }  
}  

Rule of thumb: Under normal circumstances, does not recommend the use of the first type and the second type lazy way, it is recommended to use third way a hungry man.Only when you want to implement lazy loading effect is clear, we will use the first five kinds of ways to register. If it comes to deserialize objects to create, you can try using the sixth enumeration mode. If you have other special needs, you can consider using a fourth double check the lock mode.