Sample mode - Singleton

1, Hungry Chinese:

/** * Size: Hungry Chinese * Disadvantages: Waste Space * / Public Class Singleton_HURRY {Private Static Final Singleton_HURRY HURRY = New Singleton_HURRY (); // Constructor Privatization Private Singleton_HURRY () {System.out () {System.out () {System.out .println ("Successfully Create Object!" + System.currentTimeMillis ());} / ** * Provides public methods to get instances * @return * / public static singleleton_hurry getInstance () {Return hurry;} public static void main (String [] args) {Singleton_Hurry h1 = Singleton_Hurry.getInstance (); Singleton_Hurry h2 = Singleton_Hurry.getInstance (); System.out.println (h1.hashCode ()); // 1265094477 System.out.println (h2.hashCode () ); // 1265094477}}

image

2, lazy:

/** * Size: Lazy * This kind of writing is available on a single thread, but it will appear concurrency on the multi-thread * / public class singleleton_lazy {// constructor privatization private singleleton_lazy () {System.out .println (. Thread.currentThread () getName () + "ok!");} private static Singleton_Lazy LAZY; public static Singleton_Lazy getInstance () {if (LAZY == null) {LAZY = new Singleton_Lazy ();} return LAZY Public static void main (string [] args) {for (int i = 0; I <10; i ++) {new thread (() -> {singleton_lazy.getinstance ();}). start ();}} }

image

Support multithreaded lazy:

/** * Size: Lazy * Support Multithreaded (Double Detection Lock) * Question: Do not add Volatile to cause the instruction to be row (possibly could not be created) * / public class singleleton_lazy {// constructor Privatization Private Singleton_lazy () {System.Out.println (THREAD.CURRENTTHREAD (). GetName () + "OK!");} // Avoid directive restroom private volatile static singleton_lazy lazy; public static singleleton_lazy getInstance () {// Double detection lock Sample (DCL) IF (lazy == null) {synchronized (Singleton_Lazy.class) {if (lazy == null) {lazy = new singleton_lazy (); // It is not atomic operation // 1. Assign memory Space 2. Perform a construction method, initialize the object 3. Point this object to this space}}} return lazy;}}} returnizy;} public static void main (string [] args) {for (int i = 0; i <10; i ++) {new Thread (() -> {singleton_lazy.getInstance ();}). Start ();}}}

image

3, static internal class

public class Holder {
    public static Holder getInstance(){
        return InnerClass.HOLDER;
    }

    public static class InnerClass {
        private static final Holder HOLDER = new Holder();
    }
}

The first three cases will be reflected:

public class singleleton_lazy {// constructor Privatization private singleton_lazy () {system.out.println ("THREAD.CURRENTTHREAD (). Getname () +" ok! ");} // Avoid directive rearrangement private Volatile Static Singleton_Lazy Lazy; public static singleton_lazy getInstance () {// Double detection lock mode single case (DCL) if (lazy == null) {synchronized (Singleton_lazy.class) {if (lazy == null) {lazy = new singleleton_lazy () ; // It is not atomic operation // 1. Allocate memory space 2. Perform constructing method, initialize the object 3. Point this object to this space}}} return lazy;} public static void main (String [] args) throws exception {Singleton_Lazy lazy1 = Singleton_Lazy.getInstance (); System.out.println (lazy1.hashCode ()); // single embodiment uses reflection to destroy constructor <Singleton_Lazy> constructor = Singleton_Lazy.class.getDeclaredConstructor (null); constructor.setAccessible ( True); // You can access private constructors singleton_lazy lazy2 = constructor.newinstance (); System.out.println (lazy2.hashcode ());}}

image

Solve a single case was cracked:

/** * Triple detection lock * / public class singleleton_lazy {// constructor privatization private singleleton_lazy () {singleton_lazy.class) {if (lazy! = Null) {throw new runtimeException ("Do not try to use reflection Destroying exception! ");}}} // Avoid directive rearrangement private volatile static singleleton_lazy lazy; public static singleleton_lazy getInstance () {// Double detection lock mode Size (DCL) if (lazy == null) {synchronized ( Singleton_lazy.class) {if (lazy == null) {lazy = new singleleton_lazy (); // It is not atomic operation // 1. Assign memory space 2. Perform constructive method, initialize the object 3. Point this object to this space }}} Return Lazy;} public static void main (String [] args) throws exception {singleton_lazy lazy1 = singleton_lazy.getinstance (); system.out.println (lazy1.hashcode ()); // Use reflection to destroy single case Constructor <singleton_lazy> constructor = singleton_lazy.class.getDeclaredConstructor (null); Constructor.setAccessible (TRUE); // You can access private constructors singleton_lazy lazy2 = constructor.newinstance (); system.out.println (lazy2.hashcode ());}}

image

Creating an object at this time is not a single case:

public class singleton_lazy {// constructor Privatization private singleton_lazy () {synchronized (Singleton_lazy.class) {if (lazy! = Null) {throw new runtimeException ("Do not try to use reflection destruction unusual!");}}} / / Avoid directive rearrangement private volatile static singleton_lazy lazy; public static singleleton_lazy getInstance () {// Double detection lock mode single case (DCL) {synchronized (Singleton_lazy.class) {if (Lazy = = NULL) {lazy = new singleton_lazy (); // It is not atomic operation // 1. Assign memory space 2. Perform constructive method, initialize the object 3. Point this object}}} return lazy;}} Return lazy; void main (String [] args) throws Exception {// Singleton_Lazy lazy1 = Singleton_Lazy.getInstance (); // System.out.println (lazy1.hashCode ()); // single embodiment uses reflection to destroy constructor <Singleton_Lazy> constructor = Singleton_Lazy.class.GetDeclaredConstructor (NULL); Const ructor.setAccessible (true); // access to the private constructor Singleton_Lazy lazy2 = constructor.newInstance (); System.out.println (lazy2.hashCode ()); Singleton_Lazy lazy3 = constructor.newInstance (); System.out. PRINTLN (lazy3.hashcode ());}}

image

Solution:


public class Singleton_Lazy {
    //红绿灯
    private static boolean baidou = false;

    // 构造器私有化
    private Singleton_Lazy() {
        synchronized (Singleton_Lazy.class) {
            if (baidou == false) {
                baidou = true;
            } else {
                throw new RuntimeException("不要试图使用反射破坏异常!");
            }
        }
    }

    // 避免指令重排
    private volatile static Singleton_Lazy lazy;

    public static Singleton_Lazy getInstance() {
        // 双重检测锁模式的单例 (DCL)
        if (lazy == null) {
            synchronized (Singleton_Lazy.class) {
                if (lazy == null) {
                    lazy = new Singleton_Lazy();//它不是原子性操作
                    //1.分配内存空间 2.执行构造方法,初始化对象 3.把这个对象指向这个空间
                }
            }
        }
        return lazy;
    }

    public static void main(String[] args) throws Exception {
        Singleton_Lazy lazy1 = Singleton_Lazy.getInstance();
        System.out.println(lazy1.hashCode());

        // 使用反射来破坏单例
        /*Constructor<Singleton_Lazy> constructor = Singleton_Lazy.class.getDeclaredConstructor(null);
        constructor.setAccessible(true);//可以访问私有的构造器
        Singleton_Lazy lazy2 = constructor.newInstance();
        System.out.println(lazy2.hashCode());*/

        Singleton_Lazy lazy3 = Singleton_Lazy.getInstance();
        System.out.println(lazy3.hashCode());
    }
}

image
But still can be reflected to crack