Implementation of single example in Java multithreaded programming

Source: Internet
Author: User

For ordinary single-threaded single-case, it is easier to avoid creating multiple objects, the code is as follows:

public class Singleton {      private static Singleton Singleton = null;      public static Singleton getinstance () {          if (singleton==null) {                   Singleton = new Singleton ();          }          return singleton;        }  }

This avoids the creation of multiple objects consuming system resources, or lazy loading, that is, the object is created when it is used;

In single-threaded, this class can be a perfect solution to the singleton problem, but to multi-threading, the class will have problems:

When two off-the-shelf A and B simultaneously invoke a singleton to obtain an instance, if a enters the getinstance () method, judging that the current singleton is empty, it enters Singleton=new Singeton () and returns Singleton, but when a enters, B is called simultaneously, b also determines that singleton is empty, since a enters and does not initialize, so B also enters the initialization code, initializes, and returns Singleton, which causes problems and does not implement a singleton operation.

So in the multi-threaded environment, we need to make a little change to the code, that is, to add a synchronous lock to the GetInstance method, so that A and B can not enter the method at the same time, the code is as follows:

public class Singleton {      private static Singleton Singleton = null;      public static synchronized Singleton getinstance () {          if (singleton==null) {                   Singleton = new Singleton ();          }          return singleton;        }  }

After modification, we found that before the advent of A and b at the same time access to the GetInstance method, if a first into the GetInstance method, due to the existence of sychronized, B is not possible to enter the method, a thread will be executed before the completion of the method to lock the operation, When the execution is completed, B is allowed to enter the method, and when B enters the method, Singleton is no longer null and returns a singleton singleton object directly;

But in fact, if multiple threads are called, the existence of a synchronous lock can affect program performance to a large extent, so someone later proposes the double-checked blocking method to reduce the performance impact:

There is also a method called double-check blocking, the code is as follows:

public class Singleton {      private static Singleton Singleton = null;      public static Singleton getinstance () {          if (singleton==null) {                 synchronized (Singleton) {                      if (singleton== NULL) {                           singleton = new Singleton ();}}                }          return singleton;        }  }                

After this modification, when the thread enters the GetInstance method, it will first determine whether the singleton is empty, which reduces the resources spent in the synchronization block, reduces the resource consumption, improves the performance,

It seems like this modification will not cause the synchronization lock to consume resources, nor to create multiple objects at the same time because of multithreading, but, in fact, from a deeper level, at the level of the JVM, such code can still be problematic:

Since Singleton = new Singleton () is executed, the JVM is performed in two steps, first reserving space for Singleton, assigning it directly to instance, then initializing Singleton, creating Singleton instances,

If a first enters singleton = new Ssingleton (), but only allocates space and does not initialize, it returns Singleton, and when the B thread enters, Singleton is not null. Then will directly return to the existing singleton, if the singleton real initialization before the use, the problem comes, all multithreaded singleton mode, there is a new solution:

public class singleton{     private static C lass singletoncontainer{             private static Singleton instance = new Singleto n ();     }     public static Singleton getinstance () {            return singletoncontainer.instance;     }}

This method realizes the singleton in multi-threaded environment through the inner class,

The internal mechanism of the JVM guarantees that when a class is loaded, the loading process of this class is thread-safe, and when we first call the GetInstance method, the JVM can guarantee that the instance is created only once and that initialization is done. So we no longer have to worry about instance not being created, but also implementing lazy loading singleton

Implementation of single example in Java multithreaded programming

Related Article

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.