The implementation method of the singleton pattern in the java interview (several singleton patterns)

To be honest, this question confused me. How could there be such an interview question? If you ask me the pros and cons of implementing the simple interest mode of double-checked locks, it’s ok. It’s the first time I encountered it. It’s under Baidu on the Internet. It’s really TMD. !

 

 

If you need to ensure that a class only needs one object, or creating a class requires too many resources, such as accessing IO and database operations , then you need to consider using the singleton pattern.

Key points to note when using the singleton pattern

  1. Set the constructor access modifier to private
  2. Return a singleton class object via a static method or enumeration
  3. Make sure that there is only one object of the singleton class, especially in a multi-threaded environment
  4. Make sure that singleton class objects don't rebuild the object when deserializing

Several ways to write the singleton pattern

1. Hungry Chinese

/**
 * 饿汉式实现单例模式
 */
public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {
    }

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

2. Sloth

/**
 * 懒汉式实现单例模式
 */
public class Singleton {
    private static Singleton instance;

    private Singleton() {
    }

    // synchronized方法,多线程情况下保证单例对象唯一
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

The synchronized keyword is added to the getInstance() method to make it a synchronized method, in order to ensure that the singleton object is unique in a multi-threaded environment.

Advantages:  Singletons are instantiated only when they are used, which saves resources to a certain extent.
Disadvantage:  Instantiate immediately when first loaded, slightly slower response . Synchronization occurs every time the getInstance() method is called, which consumes unnecessary resources . This mode is generally not recommended.

3. DCL (Double CheckLock) implements a singleton

/**
 * DCL实现单例模式
 */
public class Singleton {
    private static Singleton instance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        // 两层判空,第一层是为了避免不必要的同步
        // 第二层是为了在null的情况下创建实例
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }

        }
        return instance;
    }
}

优点: 资源利用率高,既能够在需要的时候才初始化实例,又能保证线程安全,同时调用getInstance()方法不进行同步锁,效率高。
缺点: 第一次加载时稍慢,由于Java内存模型的原因偶尔会失败。在高并发环境下也有一定的缺陷,虽然发生概率很小。
DCL模式是使用最多的单例模式实现方式,除非代码在并发场景比较复杂或者JDK 6以下版本使用,否则,这种方式基本都能满足需求。

4. 静态内部类

/**
 * 静态内部类实现单例模式
 */
public class Singleton {
    private Singleton() {
    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }

    /**
     * 静态内部类
     */
    private static class SingletonHolder {
        private static Singleton instance = new Singleton();
    }
}

第一次加载Singleton类时不会初始化instance,只有在第一次调用getInstance()方法时,虚拟机会加载SingletonHolder类,初始化instance。

这种方式既保证线程安全,单例对象的唯一,也延迟了单例的初始化,推荐使用这种方式来实现单例模式。

5. 枚举单例

/**
 * 枚举实现单例模式
 */
public enum SingletonEnum {
    INSTANCE;
    public void doSomething() {
        System.out.println("do something");
    }
}

默认枚举实例的创建是线程安全的,即使反序列化也不会生成新的实例,任何情况下都是一个单例

Guess you like

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