How to implement a thread-safe singleton, the premise is not locked

Singleton, I am sure you are not familiar, this is a very important Java design patterns. Learn a little bit singleton friends all know that to achieve a single case to consider concurrency problems, under normal circumstances, we will use synchronized to ensure thread safety.

So, if there is such a face questions: do not use synchronized and lock, how to implement a thread-safe singleton? How do you answer?

Candidates Class C: starving mode may be used to achieve a single embodiment. Such as:

public class Singleton { 

    private static Singleton instance = new Singleton();

    private Singleton (){}

    public static Singleton getInstance() {

      return instance;

    }

}

There are some programmers may think of starving variants:

public class Singleton {

    private Singleton instance = null;

    static {

instance = new Singleton();

    }

    private Singleton (){}

    public static Singleton getInstance() {

        return this.instance;

    }

}

Use static member variables to define static or static code, with the Class of class loading mechanism to achieve thread-safe singleton.

Interviewer: In addition to this, there are other ways you?

Class B candidates:

In addition to the above two methods, there is a way, it is to be achieved by static inner classes, as follows:

public class Singleton {

    private static class SingletonHolder {

    private static final Singleton INSTANCE = new Singleton();

}

private Singleton (){}

public static final Singleton getInstance() {

return SingletonHolder.INSTANCE;

}

}

In this way has been optimized compared to the previous two, is the use of lazy-loading. Singleton class is loaded but not initialized immediately instance. Because SingletonHolder class is not actively used, only displayed when invoking getInstance method appears SingletonHolder loading classes to instantiate instance.

Interviewer: In addition to this, there are other ways you?

A category candidates:

In addition to the above embodiment, it may also be used enumeration methods, such as:

public enum Singleton {

INSTANCE;

    public void whateverMethod() {

}

}

This approach is advocated Effective Java author Josh Bloch way, it can not only avoid multi-thread synchronization problems, but also to prevent deserialization re-create a new object, can be described as very strong barriers.

Interviewer: Several more answers, its implementation principle is the use of time by means of a singleton class loading initialization. That means the ClassLoader thread-safe mechanism.

The so-called ClassLoader thread-safe mechanism is the ClassLoader loadClass method uses synchronized keyword in the class load time. It is also because of this, unless it is overwritten, the default method throughout the loading process are synchronized, that is, to ensure the security thread.

Therefore, the above various methods, although not shown in the use of synchronized, but still achieved its underlying principle still uses synchronized.

Interviewer: In addition to this, there are other ways you?

A category candidates:

You can also use Java and contracting in the realization Lock

Interviewer: using locks or in essence, do not use the lock, then there are ways to achieve thread-safe singleton it?

A + class interviewer:

Yes, that is the use of CAS.

CAS is a term optimistic locking technique, when multiple threads attempt to use the CAS simultaneously update the same variable, only one thread can update the values ​​of variables, and other threads have failed, the failure of the thread will not be suspended, but is the failure to inform the competition, and you can try again. Examples of single-mode as follows:

public class Singleton {

    private static final AtomicReference INSTANCE = new AtomicReference();

    private Singleton() {}

    public static Singleton getInstance() {

        for (;;) {

Singleton singleton = INSTANCE.get();

            if (null != singleton) {

                return singleton;

            }

singleton = new Singleton();

            if (INSTANCE.compareAndSet(null, singleton)) {

                return singleton;

            }

        }

    }

}

Interviewer: So what advantages and disadvantages of a single case yet achieved in this way?

A ++ class interviewer:

The benefits of using CAS that does not require the use of traditional locking to ensure thread safety, CAS is a busy wait algorithm based on the underlying hardware implementation-dependent, it is not relative to the lock thread switching and blocking of additional consumption, can support larger the degree of parallelism.

An important drawback is that if CAS has been successfully executed busy waiting (been in an endless loop), will cause greater CPU execution overhead.

In addition, if the N threads to simultaneously execute singleton = new Singleton (); when there will be a lot of object creation, it is likely to lead to memory overflow.



Author: Name ape
link: https: //www.jianshu.com/p/f3fae8658f13
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/cnndevelop/p/12072735.html