Java Singleton mode learning notes

Source: Internet
Author: User

The purpose of the Singleton mode is to ensure that a class has only one instance and does not provide a global access point for it. To prevent other staff from instantiating our class,

You can create a unique constructor for this class and set the constructor's visibility to private. It is worth noting that if we create another non-private constructor or

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

Delayed initialization. There are two reasons for delayed initialization of the singleton object:
1. You may not have enough information about how to initialize a singleton object at the static initialization time.

2. the purpose of selecting lagging initialization for a singleton may be to wait for resources such as database connections, especially in applications that do not need this Singleton in certain sessions.

If the initialization of a single instance is delayed in a multi-threaded environment, we must be careful to prevent multiple threads from initializing

Generally, the singleton mode is in Java, and there are two construction methods:

Lazy mode: Global Singleton instances are built when they are used for the first time. Delayed initialization.
Hunger mode: Global Singleton instances are built during class loading. Eager to initialize.
1. Hunger type Singleton


Public class Singleton1 {

Private Singleton1 (){
}
// Define your own instance.
// Note that this is private for internal calls only

Private static Singleton1 instance = new Singleton1 ();

/***//**
* Here we provide a static method for external access to this class, which can be accessed directly.
* @ Return
*/
Public static Singleton1 getInstance (){
Return instance;
}
}

 

2. Lazy Singleton type

Public class Singleton2 {

Private static Singleton2 instance = null;
/***//**
* This method is better than the preceding method. You do not need to generate objects every time. It is only the first time.
* Instances are generated during use, improving efficiency!
* @ Return
*/
Public static Singleton2 getInstance (){
If (instance = null)
Instance = new Singleton2 ();
Return instance;
}
}


The following are the main multithreading problems. In the lazy Singleton, there is no problem with a single thread, but there may be two or more Singletion2 instances when multithreading.

For example, when thread 1 determines that instance = null is true, when the new operation is performed, after the new operation is executed and the true operation is judged, thread 2 performs the judgment operation, the instance is null. therefore, thread 2 also performs the new operation. Similarly, under high concurrency, there may be two or more Singletion2 instances. Obviously, this is incorrect.

Therefore, the code is changed as follows:

Public class Singleton3 {

Private static Singleton3 instance = null;
/***//**
* This method is better than the preceding method. You do not need to generate objects every time. It is only the first time.
* Instances are generated during use, improving efficiency!
* A synchronization flag is added for multithreading without errors.
* @ Return
*/
Public static synchronized Singleton3 getInstance (){
If (instance = null)
Instance = new Singleton3 ();
Return instance;
}

}

However, this creates another problem. The method is synchronized every time an instance is obtained. Obviously, the performance is very affected. Therefore, the code to be changed is as follows:

Note: volatile (copied online)

Volatile, replacing synchronization with a lower cost

Why is volatile cheaper than synchronization?
The synchronization cost is mainly determined by its coverage. If the synchronization coverage can be reduced, the program performance can be greatly improved.

Volatile only covers the variable level, so its synchronization cost is very low.

What is volatile?
The volatile semantics tells the processor not to put me into the working memory. Please operate on me directly in the main memory. (For details about the working memory, refer to the java Memory Model)

Therefore, when multiple cores or threads access the variable, the primary memory is operated directly, which essentially achieves variable sharing.

What are the advantages of volatile?
1. Higher program Throughput
2. Implement multithreading with less code
3. Good program scalability
4. It is easy to understand and requires no high learning costs.

What are the disadvantages of volatile?
1. prone to Problems
2. Difficult to design

 


--------------------------------------------------------------------------------

Volatile uses jdk 1.5 and later.


The improved code is as follows (double lock ):

Public class Singleton4 {
Private static volatile Singleton4 instance;
/***//**
* Dual locking for multithreading and Performance Optimization
* @ Return
*/
Public static Singleton4 getInstance ()
{
If (instance = null)
{
Synchronized (Singleton4.class) {// 1
If (instance = null) // 2
Instance = new Singleton4 (); // 3
}
}
Return instance;
}
}


Refer to the customized networking and head first design patterns.

 

 

 


The sky is vast and the sky is vast, and the wind blows the grass to see cattle and sheep

 

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.