Thread security issues in singleton Mode

Source: Internet
Author: User

In example 1, The classicsingleton. getinstance () method is thread-safe because of the following code:
If (instance = NULL)
{
Instance = new Singleton ();
}

A Method for Improving Performance

When looking for a performance improvement method, you may choose to rewrite the getinstance () method as follows:

Public static Singleton getinstance (){
If (Singleton = NULL ){
Synchronized (singleton. Class ){
Singleton = new Singleton ();
}
}
Return Singleton;
}

This code snippet only synchronizes key code, rather than the entire method. However, this code is not thread-safe. Consider the following assumption: thread 1 enters the synchronization block and thread 1 is switched before it assigns a value to the singleton member variable. Then another thread enters the if block. The second thread will wait until the first thread completes and still get two different Singleton instances. Is there any way to fix this problem? Read it.

Double lock check

At first glance, the double lock check seems to be a technology that makes lazy instantiation a thread safe. The following code snippet demonstrates this technology:

Public static Singleton getinstance (){
If (Singleton = NULL ){
Synchronized (singleton. Class ){
If (Singleton = NULL ){
Singleton = new Singleton ();
}
}
}
Return Singleton;
}
What happens if two threads access the getinstance () method at the same time? Imagine that the synchronization block of thread 1 is immediately switched. Next, the second thread enters the if block. When thread 1 exits the synchronization block, thread 2 checks again to see if the singleton instance is still null. Because the singleton member variable is set for thread 1, the second check of thread 2 will fail, and the second Singleton instance will not be created. That seems to be the case.
Unfortunately, the double lock check does not guarantee normal operation, because the compiler will assign a value to singleton randomly before the singleton constructor method is called. If thread 1 is switched after the singleton reference is assigned and before initialization, thread 2 will be returned with a reference to the uninitialized Singleton class instance.

Implementation of an improved thread-safe Singleton Mode

Example 7 lists a simple, fast, and thread-safe Singleton mode implementation:
Example 7. A simple Singleton class

Public class Singleton {
Public final static Singleton instance = new Singleton ();

Private Singleton () {// exists
}
}
This code is thread-safe because static member variables will be created when the class is accessed for the first time. You get a thread-safe implementation that automatically uses lazy instantiation; you should use it like this:

Singleton = singleton. instance; singleton. dothis (); singleton. dothat ();...

Of course everything is not perfect. Singleton is just a compromise. If you use that implementation, you cannot change it so that you may want to allow instances of multiple Singleton classes. You can change this method to return a unique instance or one of several hundred instances. you cannot use a public and static member variable to do so.

You can safely use the singleton mode of Example 7 or implement the getinstance () method with synchronization in Example 1.

 

Bytes ---------------------------------------------------------------------------------------------------

 

In fact, if you read the 8.2 singleton and thread in the book "Java Design Patterns", you will find that there will be no above problems.

8.2 singleton and thread

If you want to use delayed initialization for a singleton in a multi-threaded environment, you must be careful to prevent multiple threads from initializing the singleton at the same time. In a multi-threaded environment, we cannot guarantee that a method can continue to run until the end, and other threads can start to run the method. Therefore, two threads may attempt to initialize the singleton class almost simultaneously. If the first method finds that the Singleton is empty, and the second method starts to run at the moment, it also finds that the Singleton is empty. Next, both methods will initialize the singleton class. To prevent this type of competition, a locking mechanism is required to coordinate the running of multiple methods in different threads.

The Java Language and Its Class Libraries provide excellent support for multi-threaded development. Specifically, Java provides a lock for each object, which can be used to indicate whether the object has been occupied by a thread. To ensure that only one thread can initialize the singleton class, we can use the appropriate object lock to synchronize the singleton initialization. Other methods, such as the method that requires mutual access to the Singleton, can also be synchronized Based on the lock scheme. We recommend that you use the lock of the current class for synchronization in Java concurrent programming [Lea, 2000. The Code is as follows:

 

 

Code guarantee of getfactory (): When a thread starts to lag behind initialization, if another thread is also ready to start initialization, then the second thread will stop execution, wait for the lock of the object classlock to be obtained. When the second thread acquires the lock and starts initialization, it will find that the Singleton is no longer empty (because only the unique instance of this class exists, we can use a single static lock ).

The wipmoves variable records the number of processes that have been completed in a semi-finished product (WIP. Every time a material box is moved to a new machine, the subsystem that triggers or records the movement of the material box must call the recordwipmove () method of the factory Singleton.

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.