Multithreading in singleton Mode

Source: Internet
Author: User

I. Introduction

I am an old customer using singleton and understand how to writeCodeIt can avoid multiple threads to generate multiple instances to the maximum extent. However, Singleton is rarely used in multi-thread scenarios, so it is easy to understand.

Today we are free to figure out this issue.

Ii. Problem generation

See the following code:

 
Public class animal {Private Static animal instance = NULL; private animal () {}public static animal getinstance () {If (instance = NULL) {instance = new animal ();} return instance ;}}

It is often seen that some netizens write like this. This is suitable for writing data in most cases. We know that the operating system schedules CPU time for each independent thread. A single CPU operating system provides a time slice to the thread in rotation mode. After each thread uses the time slice, it submits the control. The system then allocates the CPU time slice to the next thread. The following code, I will make the time slice of a thread sleep simulation thread run out. The Code is as follows:

Public static animal getinstance () {If (instance = NULL) {If (thread. currentthread. name = "thread1") {thread. sleep (2000); // The time slice for simulating thread1 is used up} instance = new animal ();} return instance ;}
 
Private void beginthread () {thread th = new thread (this. run) {isbackground = true}; th. name = "thread1"; th. start (); thread Th1 = new thread (this. run2) {isbackground = true}; th2.name = "thread2"; th2.start ();} private void run () {animal p1 = people. instance;} private void run2 () {animal P2 = people. instance ;}

For example, animal P1 and animal P2 are different instances.

Of course, here we just simulate the rotation of time slice. Although it is a simulation, it can clearly explain the problem. The Singleton mentioned above has a problem. How should we write it?

I want to have two methods:

Method 1: Lock Mechanism

 
Public class animal {Private Static animal instance = NULL; Private Static object sync = new object (); Private animal () {} public static animal getinstance () {If (instance! = NULL) {lock (Sync) {If (instance = NULL) {instance = new animal () ;}} return instance ;}}

We can lock part of the Code to allow only one thread to execute at the same time. Someone has to ask: Why should I use "If (instance! = NULL )"

Because the synchronization operation is executed for a long time and consumes resources, adding a judgment on the outermost side can more efficiently implement Singleton.

It is worth noting that for the net execution mechanism, after compilation, the compilation will fine-tune our code. Since fine-tuning is likely to change the execution logic, to strictly execute the above code, you can add the volatile keyword

For example, Private StaticVolatileAnimal instance.

Method 2: If you use net for development, you can use the function of the static constructor.

 
Public sealed class people {private people () {} public static readonly people instance; static people () {instance = new people ();}}

The static constructor itself can ensure that, in the case of multiple threads, the system can ensure only one execution. Using readonly can prevent the use of instance = NULL to set the instance.

Of course, net also has other mechanisms to avoid pseudo sigleton. Please provide them.

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.