Single case mode [turn]

Source: Internet
Author: User
Tags sin static class

The following content reproduced from: http://www.yesky.com/60/1723060.shtml

single case Mode of Java schema:
As an object's creation pattern [GOF95], the singleton pattern ensures that a class has only one instance, and instantiates it and supplies the instance to the entire system. This class is called a single instance class.

Note: This is the 15th chapter of Dr. Shanhong's "Java and Schema" book.
Feature: A class can only have one instance of its own to create this instance the entire system will use this instance

Example: In the following object graph, there is a single example object, and customer A, customer B, and customer C are three client objects of a single instance object. As you can see, all client objects share a single instance object. And from the single example object to its own connection line, it can be seen that the single Case object holds its own reference.

The following content reproduced from: http://www.blogjava.net/asdtiang/archive/2011/03/15/346289.html

The purpose of the Singleton mode is to ensure that a class has only one instance, and does not provide a global access point. To prevent other workers from instantiating our class, you can create a unique constructor for the class and set the visibility of the builder to private. It is worth noting that if we create other non-proprietary constructors or do not provide constructors for the class at all, other people can instantiate our class. If you do not want to create a single object in advance, we can wait to create it when we first use the single Instance object, that is, lazy initialization. There are two reasons to delay initializing a single Instance object: perhaps at static initialization time, you don't have enough information about how to initialize a single instance object. The purpose of selecting a lag initialization single case may be to wait for resources, such as database connections, especially in applications that do not need this single example in certain sessions.

If you are using lazy initialization for a single example in a multithreaded environment, then we must be careful to prevent multiple threads from initializing the

Typically, a singleton pattern is in the Java language, and there are two ways to build it: The lazy way: a singleton instance of the global is built the first time it is used. Lazy initialization. A hungry man: The Global Singleton instance is built when the class is loaded. eagerly initialized.

In the lazy single case, single-threaded is not a problem, but multiple threads can have two or more instances of Singletion2.
For example: Thread 1 when judging instance==null as true, sweeping the new operation, before performing the new operation, after the judge is true, thread 2 performs the judgment operation, then instance is still null. Therefore, thread 2 also performs the new operation. By analogy, under high concurrency, there may be two or more instances. Obviously, this is not true. So you need to add synchronized.

The following seven methods are reproduced from: http://cantellow.iteye.com/blog/838473

First (lazy, thread unsafe):

Public class Singleton {private static Singleton instance, public static Singleton getinstance () {if (instance = = Nu ll) {instance = new Singleton ();} return instance; } }

second (lazy, thread safe):

Public class Singleton {private static Singleton instance, public static synchronized Singleton getinstance () {if (i Nstance = = NULL) {instance = new Singleton ();} return instance; } }

The third type (a Hungry man):

Public class Singleton {private static Singleton instance = new Singleton (), public static Singleton getinstance () { return instance; } }

This method avoids multithreading synchronization problems based on the Classloder mechanism, however, instance is instantiated when class is loaded, 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 lead to class loading, when initialization instance obviously does not achieve the lazy loading effect.

fourth species ( hungry Han, variant):

Public class Singleton {private Singleton instance = null; static {instance = new Singleton ();} public static Singl Eton getinstance () {return this.instance;}}

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

fifth (Static internal class):

Public class Singleton {private static class Singletonholder {private static final Singleton INSTANCE = new Singleto N (); public static final Singleton getinstance () {return singletonholder.instance}}

This approach also takes advantage of the classloder mechanism to ensure that there is only one thread to initialize the instance, which differs from the third and fourth way (a very subtle difference): The third and fourth way is if the Singleton class is loaded, then instance is instantiated (does not reach the lazy loading effect), and this way Singleton class is loaded and instance is not necessarily initialized. Because the Singletonholder class is not actively used, the load Singletonholder class is displayed only when the GetInstance method is called, thus instantiating the instance. Imagine if instantiating instance is consuming resources, I want him to delay loading, on the other hand, I don't want to instantiate the Singleton class when it's loaded, because I can't make sure that the Singleton class can also be actively used in other places to be loaded, so this time instantiating Instance is clearly not appropriate. This is a reasonable way to compare the third and fourth ways.

Sixth (enum):

Public enum Singleton {INSTANCE. public void Whatevermethod () {}}

This is a way that effective Java author Josh Bloch advocated, not only to avoid multithreading synchronization problems, but also to prevent deserialization of new objects to be recreated, is a very strong barrier ah, but, personally think because of 1.5 to join the enum characteristics, Writing in this way can not help but feel unfamiliar, in the actual work, I also rarely see someone wrote this.

The seventh type (double check lock):

Public class Singleton {Private volatile static Singleton Singleton; public static Singleton Getsingleton () {if (sin Gleton = = null) {synchronized (Singleton.class) {if (Singleton = = null) {Singleton = new Singleton ();}}} return sing Leton; } }

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

After JDK1.5, the double check lock can achieve the single case effect normally.

Summary

There are two issues to note:

1. If the singleton is loaded by a different class loader, there may be instances of multiple singleton classes. The assumption is not remote access, for example, some servlet containers use a completely different class loader for each servlet, so that if two servlet accesses a singleton class, they all have their own instances.

2. If the singleton implements the Java.io.Serializable interface, then instances of the class may be serialized and recovered. However, if you serialize an object of a singleton class and then recover multiple objects, you will have multiple instances of the Singleton class.

The way to fix the first problem is to:

private static Class GetClass (String classname) throws ClassNotFoundException {ClassLoader ClassLoader = Thread.currentt Hread (). Getcontextclassloader (); if (ClassLoader = = null) ClassLoader = Singleton.class.getClassLoader (); Return (Classloader.loadclass (classname)); } }

The way to fix the second problem is to:

public class Singleton implements java.io.Serializable {public static Singleton INSTANCE = new Singleton (); protected Sin Gleton () {} private Object Readresolve () {return INSTANCE}}

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 would use a third way, and only use the fifth way to explicitly implement the lazy loading effect, in addition, When it comes to deserialization to create an object, I try to use enumerations to implement the single example, however, I always guarantee that my program is thread safe, and I will never use the first and second way, and if there are other special needs, I might use the seventh way, after all, JDK1.5 has no problem with double check locking.

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

Superheizai students summed up the very place:

In general, however, the first is not a single case, the fourth and third is one, if the calculation, the fifth can also be written separately. Therefore, the general single case are five kinds of writing. Lazy, Evil-han, double check locks, enumerations and static inner classes.

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.