singleton pattern

singleton pattern

public class Singleton {

private static Singleton uniqueInstance;

private Singleton() {}

public static synchronized Singleton getInstance()
{
    if(uniqueInstance==null)
    {
        uniqueInstance=new Singleton();
    }
    return uniqueInstance;
}
}

By adding the synchronized keyword to the getInstance() method, we force each thread to wait until other threads leave the method before entering this method. That is, no two threads can enter this method at the same time.

1. If the performance of getInstance() is not critical to the application, do nothing

The method of synchronizing getInstance() is simple and effective, however, synchronizing a method may result in a 100 times decrease in program execution efficiency. Therefore, if you use the getInstance() routine in heavily used places, you may have to reconsider.

2. Use "eager" creation of instances instead of delayed instantiation

public class Singleton {

private static Singleton uniqueInstance=new Singleton();

private Singleton() {}

public static Singleton getInstance()
{
    return uniqueInstance;
}
}

With this approach, we rely on the JVM to create this unique singleton instance as soon as the class is loaded. The JVM guarantees that this instance must be created before any thread accesses the uniqueInstance static variable.

3. Use "double check locking" to reduce the use of synchronization in getInstance()

public class Singleton {

private volatile static Singleton uniqueInstance;

private Singleton() {}

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324862370&siteId=291194637