Recently saw an article about instance in Java (http://www.zhihu.com/question/29971746), triggering some thoughts on the singleton pattern and collecting some articles on Java singleton patterns from the Internet, summarized as follows:
First, put out three simple code for a single case design:
1. Lazy Loading--delay loading without regard to efficiency issuesPublic class singleton{private static SingleTon instance = null;Public static synchronized SingleTon getinstance () {if (instance==null) {instance = new SingleTon (); } }}2. The basic implementation of instant loadingPublic class SingleTon () {private static SingleTon instance = new SingleTon ();Public static SingleTon getinstance () {return instance; }}3.Double Check Mode--the key consideration is whether the performance improvement of the returned result in the concurrency environment can offset the more than two judgment jumpsPublic 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 (); } } }returnUniqueinstance; }}
Analysis:The 1, 1th and 2nd approaches, which only consider the issue of efficiency, if not the case of a "single explosion" (there are a number of different instances in the system ,with instant loading, these useless instances are loaded at the same time: Inefficient), delayed loading and immediate load efficiency are not much different ...2, the 3rd type DCL (Double check lock), two check instance==null, the first to avoid each lock, to avoid a certain lock-up overhead;second judgment in order to avoid the problem of synchronization, such as: 10 Threads calling the GetInstance () method at the same time, both performed the first step of checking instance = = NULL, and one of the threads successfully acquired the
lock (executes the synchronized statement), then if you do not again judge instance = = NULL, then 10 threads will generate 10 objects, which violates the original intention of the Singleton, where the DCL is concerned about the cost:
the main starting point of using the Doublecheck method is "Avoid the initialization overhead of the synchronization lock itself", rather than "avoid the execution overhead of locked content", which is greater than the overhead of locking and the cost of conditional judgment. Another feature is that volatile is added to the type declaration of the variable instance because the statement that creates the object below is not an atomic operation, and volatile can make it atomic, avoiding synchronization problems
3 implementation methods and characteristics of Java single-case mode