Multithreaded under Singleton mode: Lazy loading (deferred loading) and instant loading

Source: Internet
Author: User
Tags mutex static class
In development, if an instance is created that consumes a lot of system resources, we typically use lazy loading mechanisms, which means that this instance is created only when this instance is used, which is widely used in singleton mode. The implementation of this mechanism in single-threaded environment is very simple, but there are hidden dangers in the multi-threaded environment. This article focuses on the lazy loading mechanism and its use in multi-threaded environments. (author Numberzero, refer to the IBM article "double-checked locking and the Singleton pattern", welcome reprint and discussion)

1. Lazy loading of a singleton mode
Usually when we design a singleton class, we construct the class inside the class (either by constructor or directly at the definition), and provide a static getinstance method to provide a way to get the singleton object. For example:

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

The disadvantage of this code is that the first time the class is loaded with the creation of the singleton instance, the result is different from what we expected because it might not be the time we need this instance to create the instance. At the same time, if the creation of this singleton instance consumes system resources, and the application never uses the singleton instance, then the system resources created singleton consume are wasted.

To avoid this, we usually use lazy loading mechanisms, which are used to create them. The lazy loading code for the above code is as follows:

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

2. Problem of lazy loading in multi-threading
First extract the Lazy loaded code:

1 public static Singleton getinstance () {        
2     if (instance = = null)        
3     instance = new Singleton ();         
4     return instance;         
5}      

This is if two threads A and B execute the method at the same time, and then execute as follows: A enters if judgment, at this time foo is null, so enter if B enters if judgment, at this point A has not created Foo, so foo is also null, so B also enters if a creates a Foo and returns b also creates a Foo and returns

The problem arises and our singleton was created two times, which is not what we expected.

3 solutions and their existing problems
  3.1 Using the class lock mechanism
The most straightforward solution to the above problem is to add a synchronize prefix to the GetInstance method so that only one off-the-shelf call getinstance method is allowed at a time:

1 public static synchronized Singleton getinstance () {        
2     if (instance = = null)        
3     instance = new Singleton ( );         
4     return instance;         
5}      

This solution does prevent errors, but it does affect performance: Singleton locks must be obtained each time the GetInstance method is called, and in fact, after the singleton instance is created, subsequent requests do not need to use the mutex again.

3.2 double-checked Locking
In order to solve the above problems, some people have put forward the double-checked locking solution.

1 public static Singleton getinstance () {        
2     if (instance = = null)        
3         synchronized (instance) {        
4             if (instance = = null)        
5                 instance = new Singleton ();        
6         }        
7     return instance;         
8}

Let's take a look at how this code works: first, when a thread makes a request, it checks whether instance is null, and if not, returns its contents directly, thus avoiding the resources required to enter the synchronized block. Second, even if the situation mentioned in section 2nd occurs, and two threads enter the first if judgment at the same time, they must also execute the code in the synchronized block sequentially, and the first thread that enters the code block creates a new singleton instance. Subsequent threads do not create redundant instances because they cannot be judged by IF.

The above description seems to have solved all the problems we face, but in fact, from the JVM's point of view, the code can still be wrong.

For the JVM, it executes a Java instruction. creating objects and assigning operations in Java directives is done separately, that is, instance = new Singleton (), and the statements are executed in two steps. However, the JVM does not guarantee the sequencing of the two operations, which means that it is possible for the JVM to allocate space for the new singleton instance and then assign the value directly to the instance member before initializing the singleton instance. This makes the error possible, we still take A, b two threads as an example: A, b thread at the same time enter the first if judge a first into the synchronized block, because instance is null, so it executes instance = new Singleton (); Because of the optimization mechanism inside the JVM, the JVM first draws some blank memory allocated to the singleton instance and assigns it to the instance member (note that at this point the JVM does not start initializing the instance), and a leaves the synchronized block. B enters the synchronized block because instance is not NULL at this time, so it immediately leaves the synchronized block and returns the result to the program that called the method. At this point the B thread intends to use the singleton instance, but finds that it has not been initialized and that the error occurred.

4 Implementing a singleton pattern in a multithreaded environment through an internal class
The best and most convenient workaround is to implement slow loading and do not want to be mutually exclusive when calling GetInstance:

1 public class singleton{        
 2     Private Singleton () {        
 3         ...        
 4     }        
 5     private static class singletoncontainer{        
 6         private static Singleton instance = new Singleton ( );        
 7     }        
 8 public     static Singleton getinstance () {        
 9         return singletoncontainer.instance;        
Ten     }        
11}

The mechanism inside the JVM guarantees that when a class is loaded, the loading process of the class is thread-exclusive. So when we first call getinstance, the JVM can help us ensure that instance is only created once, and that the memory assigned to instance is initialized, so we don't have to worry about the 3.2 issue. In addition, the method will only use the mutex at the first call, which solves the inefficient problem in 3.1. The last instance is created the first time the Singletoncontainer class is loaded, and the Singletoncontainer class is loaded when the GetInstance method is called, so it also implements lazy loading.

Transferred from: http://www.cnblogs.com/jingpeipei/p/5771716.html

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.