Java multi-thread security Singleton

Source: Internet
Author: User
// Non-thread security. This processing method works well in single-thread mode, but may cause problems in multi-thread mode. If the first thread finds that the member variable is null, it is ready to create an object. This is the second thread, and it also finds that the member variable is null, it also creates a new object. This results in multiple Singleton instances in one JVM. If the member variables of this Singleton type change during the running process, it may cause inconsistency among multiple Singleton type instances, resulting in some strange phenomena. For example, a service process stops multiple thread services by checking a certain attribute of the singleton object. If there are instances of multiple Singleton objects, some thread services will stop, some thread services cannot be stopped

  public class TestService{    private static TestService instance = null;
    private TestService() {
    }

    
    public static TestService getInstance() {      if (instance == null) {        instance=new TestService();      }      return instance;    }  }

// Thread security this processing method introduces the synchronization code, but because this synchronization code will only be executed once or multiple times at the beginning, the performance of the entire system will not be affected.

  public class TestService{    private static TestService instance = null;
    private TestService() {
    }
    private static synchronized void syncInit() {      if (instance == null) {        instance = new TestService();      }    }
    public static TestService getInstance() {      if (instance == null) {        syncInit();      }      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.