Seven ways to style a single case

Source: Internet
Author: User
Tags class manager knowledge base

Reprint Please specify source: http://cantellow.iteye.com/blog/838473

The first type (lazy, thread insecure):

Java code
    1. public class Singleton {
    2. private static Singleton instance;
    3. Private Singleton () {}
    4. public static Singleton getinstance () {
    5. if (instance = = null) {
    6. Instance = new Singleton ();
    7. }
    8. return instance;
    9. }
    10. }

This type of lazy loading is obvious, but the fatal is that the multithreading does not work properly.

The second type (lazy, thread safe):

Java code
    1. public class Singleton {
    2. private static Singleton instance;
    3. Private Singleton () {}
    4. public static synchronized Singleton getinstance () {
    5. if (instance = = null) {
    6. Instance = new Singleton ();
    7. }
    8. return instance;
    9. }
    10. }

This notation works well in multi-threading, and it seems to have a good lazy loading, but, unfortunately, is inefficient and does not require synchronization in 99% cases.

The third type (a Hungry man):

Java code
    1. public class Singleton {
    2. private static Singleton instance = new Singleton ();
    3. Private Singleton () {}
    4. public static Singleton getinstance () {
    5. return instance;
    6. }
    7. }

This approach avoids multi-threaded synchronization problems based on the Classloder mechanism, however, instance is instantiated at class loading, although there are many reasons for class loading, most of which are called getinstance methods in singleton mode. However, it is not certain that there are other ways (or other static methods) that cause the class to load, when initializing instance obviously does not achieve the effect of lazy loading.

The fourth type ( hungry Han, variant):

Java code
    1. public class Singleton {
    2. Private Singleton instance = null;
    3. static {
    4. Instance = new Singleton ();
    5. }
    6. Private Singleton () {}
    7. public static Singleton getinstance () {
    8. return this.instance;
    9. }
    10. }

The surface looks very different, in fact, the third Way is similar, all in class initialization is instantiated instance.

The fifth type (static inner Class):

Java code
    1. public class Singleton {
    2. private Static Class Singletonholder {
    3. private static final Singleton INSTANCE = new Singleton ();
    4. }
    5. Private Singleton () {}
    6. public static final Singleton getinstance () {
    7. return singletonholder.instance;
    8. }
    9. }

This approach also takes advantage of the classloder mechanism to ensure that there is only one thread initialized instance, which differs from the third and fourth ways (very subtle differences): The third and fourth ways are as long as the Singleton class is loaded, Then instance will be instantiated (without the lazy loading effect), and this is singleton class is loaded, instance not necessarily initialized. Because the Singletonholder class is not actively used, the load Singletonholder class is displayed only if it is displayed by calling the GetInstance method, thus instantiating the instance. Imagine if instantiating instance is draining resources, I want him to delay loading, on the other hand, I don't want to instantiate when the singleton class loads, because I can't make sure that the Singleton class can be actively used in other places to be loaded, It is obviously inappropriate to instantiate instance at this time. At this point, this approach is reasonable compared to the third and fourth approaches.

The sixth type (enumeration):

Java code
    1. public enum Singleton {
    2. INSTANCE;
    3. public void Whatevermethod () {
    4. }
    5. }

This approach is advocated by effective Java author Josh Bloch, which not only avoids multi-threaded synchronization problems, but also prevents deserialization from recreating new objects, which is a very strong barrier, but, personally, because the enum attribute is added in 1.5, Writing in this way makes people feel unfamiliar, and in practical work, I seldom see anyone write like that.

Seventh type (double check lock):

Java code
  1. public class Singleton {
  2. Private volatile static Singleton Singleton;
  3. Private Singleton () {}
  4. public static Singleton Getsingleton () {
  5. if (singleton = = null) {
  6. Synchronized (Singleton.class) {
  7. if (singleton = = null) {
  8. Singleton = new Singleton ();
  9. }
  10. }
  11. }
  12. return singleton;
  13. }
  14. }

This is the second way of the upgrade version, commonly known as double check Lock, detailed information please see: http://www.ibm.com/developerworks/cn/java/j-dcl.html

After JDK1.5, the double-check lock is able to achieve a single-case effect normally.

Summarize

There are two issues to note:

1. If a singleton is loaded by a different class loader, there may be instances of multiple singleton classes. It is assumed that not remote access, such as some servlet containers, use a completely different class loader for each servlet, so that if there are two Servlets accessing a singleton class, they will have their own instance.

2. If the singleton implements the Java.io.Serializable interface, then instances of this class may be serialized and restored. In any case, if you serialize an object of a singleton class and then restore multiple objects, you will have multiple instances of the Singleton class.

The fix for the first problem is:

Java code
  1. private static Class GetClass (String classname)
  2. Throws ClassNotFoundException {
  3. ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader ();
  4. if (ClassLoader = = null)
  5. ClassLoader = Singleton.class.getClassLoader ();
  6. Return (Classloader.loadclass (classname));
  7. }
  8. }

The fix for the second problem is:

Java code
    1. public class Singleton implements Java.io.Serializable {
    2. public static Singleton INSTANCE = new Singleton ();
    3. Protected Singleton () {
    4. }
    5. Private Object Readresolve () {
    6. return INSTANCE;
    7. }
    8. }

For me, I prefer the third and fifth way, easy to understand, and thread-safe in the JVM layer (if not multiple classloader environments), in general, I will use the third way, only if you want to explicitly implement the lazy loading effect will be used in the fifth way, in addition, If it involves deserializing the creation of an object I will try to implement the singleton using enumerations, but I will always ensure that my program is thread safe, and I will never use the first and second way, if there are other special needs, I may use the seventh way, after all, JDK1.5 has no problem with double-check locking.

========================================================================

Superheizai students summed up in place:

However, in general, the first is not a single case, the fourth and the third is a kind, if counted, the fifth can also be written separately. Therefore, the general single case is five kinds of writing. Lazy, bad Han, double check lock, enumeration and static inner class.

I am glad to have such a reader, together with mutual encouragement.

the
Top Ten
Step to share: Experience in the year-end summary (dehydrated version) | One of the refactoring practices
    • 2010-12-10 13:02
    • Browse 181520
    • Comments (54)
    • Category: Programming languages
    • Related recommendations
Reference Knowledge Base
C # Knowledgebase 246 concern | 306 Included
Virtual Reality (VR) Knowledgebase 592 Attention | 166 included
node. JS Knowledge Base 398 concern | 246 included
Algorithmic and data Structure Knowledgebase 1858 Attention | 2466 included
Comments 54 Floor Bocurry 2016-04-19 The fourth kind, static method can not use this of it. 53 Floor Mr.cheney 2015-08-28 this: Mr.cheney writes that there is also a class loading mechanism that leverages the JVM,
It is thread-safe and is only created when it is used (taking advantage of the Java Virtual machine's class loading feature)
Java code
    1. public class Managerholder {
    2. public static Manager Managerholder = new manager ();
    3. }
    4. public class Manager {
    5. public static Manager GetInstances () {
    6. return managerholder.managerholder;
    7. }
    8. }
52/F Mr.cheney 2015-08-28 There is also a class loading mechanism that leverages the JVM,
It is thread-safe and is only created when it is used (taking advantage of the Java Virtual machine's class loading feature)
Java code
    1. public class Managerholder {
    2. public static Manager Managerholder = new manager ();
    3. }
    4. public class Managerholder {
    5. public static Manager Managerholder = new manager ();
    6. }
51 Floor tianyi1 2015-06-15 Fourth kind of problematic 50 floor h416373073 2015-01-13 Huntfor wrote lee372106501 wrote that fourth obviously has a problem with static code blocks that can access non-static variables? This can be written in a static method. This is not a trick, you compile can pass the AH
Top
49 Floor Huntfor 2014-09-10 lee372106501 wrote the fourth obvious problem is that static code blocks can access non-static variables? This can be written in a static method. This is not a trick, you compile can pass the AH
Top 48 Floor lee372106501 2014-09-08 The fourth kind of obvious problem is, static code block can access non-static variables? This can be written in a static method. This is not a trick, you compile can pass the AH 47 floor Fs_plane 2014-07-01 Some people say double check doesn't make sense
It really doesn't make sense before jdk1.5.
However, after the JDK Milestone version 1.5, it makes sense and is now widely used because of the introduction of modifier volatile

That's why jdk1.5 can use double-check 46 floor h4x0r 2014-05-13 Ask, New Singleton () What if you need to pass parameters to instantiate? The third Way 45 floor Newlinuxjava 2013-12-06 I do not know Bo Master can provide the next multi-threaded test code, mainly want to see the above example to reproduce the problem. 44 Floor jis117 2013-10-19 Cantellow wrote Senton wrote the fourth species (a Hungry man, variant):
How do I get an instance of singleton?
Oh, you are too careful, it is my fault. I corrected.
It hasn't changed. 43 floor Cantellow 2011-09-23 NOCB wrote I wrote a singleton, on Tomcat6, a servlet put data, a get data.
In the PC browser, mobile phone browser is not a problem, but the colleague wrote a mobile app, send the request, found that the singleton into 2 objects. Very strange. I wonder if there is any experience in this area? Thank you
The reason for this is the ClassLoader, like this application, let the Web server to ensure that the singleton is not suitable, more Web servers, you can use other methods, such as on the Memcache 42 floor NOCB 2011-09-22 I wrote a single case, on the TOMCAT6, A servlet put data, a get data.
In the PC browser, mobile phone browser is not a problem, but the colleague wrote a mobile app, send the request, found that the singleton into 2 objects. Very strange. I wonder if there is any experience in this area? Thank you, 41 floor, NOCB. 2011-09-22 Hello, excuse me, what is the solution to the loading problem of different loaders?
You write not understand, my single-case how to write, how to call it? 40 Floor cymx09 2010-12-24 Your 7 ways are good. However, it is best to add private constructs to each: to prevent external direct new Singleton () in order to truly guarantee the singleton.
Private Singleton () {

} 39 floor xiaohui886688 benefited from 2010-12-21, ...
38 Floor morning sun 2010-12-17 If you use a third type, the proposal is final, because there is no reason why we should not declare it final. In addition, about double locking, it is recommended that you look at the CacheManager class in the source code of Ehcache, new strength, should return in the synchronized block, the rest of the same, including the declaration of the instance as atomic.
Attached Ehcache Project CacheManager part of the source code:
Java code
  1. public static CacheManager Create () throws Cacheexception {
  2. if (singleton! = null) {
  3. return singleton;
  4. }
  5. Synchronized (Cachemanager.class) {
  6. if (singleton = = null) {
  7. Log.debug ("Creating new CacheManager with default Config");
  8. Singleton = new CacheManager ();
  9. } else {
  10. Log.debug ("Attempting to create an existing singleton. Existing Singleton returned. ");
  11. }
  12. return singleton; This is returned within the synchronized block, and your example is not
  13. }
  14. }
37 Floor Yunchow 2010-12-17 make so much uninteresting, direct a hungry man is kingly 36 floor KYFXBL 2010-12-17 suggest you to study in depth "anise" 4 kind of wording 35 floor Guyinglong 2010-12-16 Publi C Class Singleton {
/**
* Class-Level inner class, which is a static member-inner class, an instance of the inner class and an instance of the outer class
* There is no binding relationship, and only the call is loaded, which allows for lazy loading
*/
private Static Class singletonholder{
/**
* Static initializers, which are guaranteed by the JVM for thread safety
*/
private static Singleton instance = new Singleton ();
}
/**
* Privatization Structuring method
*/
Private Singleton () {
}
public static Singleton getinstance () {
return singletonholder.instance;
}
}

Tall man wrote it.

Seven ways to style a single case

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.