A single example model of Java design Model _java

Source: Internet
Author: User
Tags volatile

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's worth noting that if we create other non proprietary constructors, or simply do not mention the class

For the constructor, then other people can still instantiate our class. If you do not want to create a single object in advance, we can wait to create it the first time we use the single Instance object, that is,

Lazy initialization. There are two reasons to delay initialization of a single Instance object:

1. Perhaps in the static initialization time, you do not have enough information about how to initialize a single instance object.

2. 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, there are two ways to build a single case pattern in the Java language:

Lazy Way: The global Singleton instance 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.

1, a hungry man type Single case class

The public class Singleton1 {
 
 private Singleton1 () {
 }
 //defines itself as an instance within itself.
 Note that this is private only for internal calls

 private static Singleton1 instance = new Singleton1 ();

 /** *//**
 * Here provides a static method for external access to this class, direct access to
 * @return
 /public
 static Singleton1 getinstance () { Return
 instance
 }
}

2, the lazy type single case class

public class Singleton2 {

 private static Singleton2 instance = null;
 /** *//**
 * This method is better than the above, do not have every time to generate objects, only the first time
 * Use to generate instances, improve efficiency!
 * @return
 *
 /public static Singleton2 getinstance () { 
 if (instance = null)
 instance = new Sing Leton2 ();
 return instance
 }
}

The following main multithreading problem, in the lazy single example, single-threaded is not a problem, but multiple threads will likely appear 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 of Singletion2. Obviously, this is not true.

So change the code as follows:

public class Singleton3 {

 private static Singleton3 instance = null;
 /** *//**
 * This method is better than the above, do not have every time to generate objects, only the first time
 * Use to generate instances, improve efficiency!
 * for multiple threading error, add Sync flag
 * @return/public
 static synchronized Singleton3 getinstance () { 
 if ( instance = = NULL)
 instance = new Singleton3 ();
 return instance
 }

}

But this creates a problem where the method is synchronized each time the instance is fetched, and obviously the performance is very affected, so keep changing the code as follows:

volatile, replacing synchronization with a lower price

Why is the use of volatile lower than the cost of synchronization?
The cost of synchronization is mainly determined by its coverage, and if you can reduce the coverage of synchronization, you can significantly improve program performance.

And volatile's coverage is variable-level only. Therefore, its synchronization cost is very low.

What is the volatile principle?

Volatile's semantics, in fact, is to tell the processor, do not put me into working memory, please directly in main memory operation of me. (The working memory is detailed in the Java memory model)

Therefore, when multi-core or multithreading accesses the variable, it will directly manipulate main memory, which is essentially a variable sharing.

What are the advantages of volatile?
1, larger program throughput
2, less code to implement multithreading
3, the program's scalability is better
4, better understanding, do not need too high cost of learning

What's the disadvantage of volatile?
1, easy to go wrong
2, more difficult to design

Volatile using JDK requires 1.5 version and more than 1.5.

The improved code is as follows (also called Double Lock):

public class Singleton4 {
 private static volatile Singleton4 instance;
 /** *//**
 * Double lock for multi-threaded application and performance optimization
 * @return
 /public
 static Singleton4 getinstance ()
 {
 if ( instance = = null)
 {
 synchronized (singleton4.class) {//1
 if (instance = null)//2
 instance = new Sin Gleton4 (); 3
 }
 } return
 instance
 }

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.