In Java, are you sure you have a pair of singleton?

Source: Internet
Author: User
Tags volatile

As programmers such special species, have mastered a special ability is the programming idea, logic is more cautious, but sometimes always ignore some details, for example, I always think Singleton is the simplest design pattern, do not care too much, However, it is because this is not intended to be a disadvantage in development. Really too young and simple.
No nonsense, straight into the subject.

In the Code of the world found there are various forms of the single case, some people say that there are 5 kinds of single cases, 6 kinds, 7 kinds ...
For the classification of Singleton this must be regulated, first of all, so many classifications are based on what to define, what is the benchmark?

Otherwise how can have so many wording.

Thus summed down, from 延迟载入 运行效率 the point of view and the main is divided into two, a hungry man as the name implies is the operation of high efficiency, but the lack of delay loading, the other way almost the same is lazy type of a development, or optimization evolved, the following see Code.

Commonly used in the development of single-a Hungry man type
publicclass SingletonDemo1 {    privatestaticfinalnew SingletonDemo1();    publicstaticgetInstance() {        return s1;    }    privateSingletonDemo1() {    }}

Yes, that's right. The above code is called 单例-饿汉式 , a hungry man style has always been high efficiency and is known in the single case, so the development of the common use of the singleton model will also choose him, simple and useful.
>

Development evaluation: ★★★★☆
Delay Loading: ★☆☆☆☆
Operating efficiency: ★★★★★

Time-consuming snail-the lazy type
publicclass SingletonDemo2 {    privatestatic SingletonDemo2 s1;    publicstaticsynchronizedgetInstance() {        ifnull) {            new SingletonDemo2();        }        return s1;    }    privateSingletonDemo2() {    }}

In hello world This world all know that such a singleton is basically not going to be used in

Double check lock-lazy type

This can be said to be a microcosm of the above a hungry man style, why so, because he is not perfect, still have a bug.

 Public  class SingletonDemo3 {    Private StaticSingletonDemo3 S1; Public StaticSingletonDemo3getinstance() {if(S1 = =NULL) {//Use a temporary variable hereSingletonDemo3 instance;synchronized(Singletondemo3.class) {instance = S1;if(Instance = =NULL) {synchronized(Singletondemo3.class) {if(Instance = =NULL) {instance =NewSingletonDemo3 ();                }} S1 = instance; }            }        }returnS1; }}

This approach is mainly through if inferred non-null instances, improve the efficiency of the operation, do not have to be synchronize every time getInstace , only to synchronize for the first time, there is no need to create.

But why is there a bug in this writing? This problem is mainly caused by the internal model of the JVM layer in Java. The simple point is that the problem has been instance引用的对象有可能还没有完毕初始化完就直接返回该实例过去 optimized after the jdk1.5, and it's not much to say that you can look at this blog post well.
See details

There are, of course, some solutions.
    • Using the volatile keyword to resolve a double-check lock bug, the volatile keyword is another scenario in Java that addresses visibility and ordering issues.
 Public  class safedoublecheckedlocking {//Added the volatile keyword    Private volatile StaticInstance Instance; Public StaticInstancegetinstance() {if(Instance = =NULL) {synchronized(Safedoublecheckedlocking.class) {if(Instance = =NULL) Instance =NewInstance ();//instance is volatile. No problem now.}        }returnInstance }}

>

Development evaluation: ★★★☆☆
Delay Loading: ★★★☆☆
Operating efficiency: ★★★☆☆

Recommended static inner class-lazy type
 Public  class SingletonDemo4 {    //Instantiate an object by means of a static inner class    Private Static  class Innersingleton {        Private Static FinalSingletonDemo4 instance =NewSingletonDemo4 (); } Public StaticSingletonDemo4getinstance() {returnInnersingleton.instance; }Private SingletonDemo4() {    }}

This week the way is to take advantage of some of the characteristics of class loading, in the Classloder mechanism, the initialization of instance only one thread, and this way another advantage is the effect of delay loading, when SingletonDemo4 loaded, but the inner class InnerSingleton is not loaded, because InnerSingletonno active use, only by invoking the getInstance method will be loaded into InnerSingleton the class, and then the instance private static final SingletonDemo4 instance = new SingletonDemo4();
So this ingenious way is safer and more efficient than a double-check lock.
>

Development evaluation: ★★★★☆
Delay Loading: ★★★★☆
Operating efficiency: ★★★★☆

Recommended enumeration-A hungry man type
publicenum SingletonDemo5 {    //枚举元素本身就是一个单例(名字能够任意定义);    INSTANCE;    //能够做一些单例的初始化操作    publicvoidsingletonOperation() {    }}

This way is actually very handsome, but in the actual development of very few people used, this is a bit strange, first of all, enum itself is a singleton, and enumerate another feature, to avoid the release of serialization and reflection to solve a single case problem, the manager no longer worry about single case security, may be 1.5 only enum reason it, If the project is appropriate, you can try this single example.
>

Development evaluation: ★★★★☆
Delay Loading: ★★★★☆
Operating efficiency: ★★★★☆

To summarize:

There are advantages to each of the following singleton, as to which of these can be chosen according to your business needs.

    • A Hungry man
      • Standard A Hungry man (Safety protection aspect enumeration single example better than standard a hungry man)
        Thread-safe, efficient, and not lazy to load
      • Enumeration single Example
        Thread-safe, efficient, lazy loading (natural avoidance of reflection and deserialization)
        ?
    • Lazy (Static inner class of efficiency is better than standard idler)
      • Standard lazy
        Thread-safe, inefficient, lazy to load
      • Double detection (not recommended, bug)
        Thread-safe, inefficient, lazy to load
      • Static Inner class
        Thread-safe, inefficient, lazy to load
        ?

For the security of the single case, can continue your handsome reading posture, Java in your case is not always naked

In Java, are you sure you have a pair of singleton?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.