Locking in single instance mode

Source: Internet
Author: User

Singleton is responsible for creating its own unique instance and defining an instance method to allow customers to access the instance.
Iii. Example
Let's take a look at the simplest single-piece mode implementation example.

1 class simplesingleton
2 {
3 privatestatic simplesingleton _ instance;
4
5 private simplesingleton ()
6 {
7}
8
9 publicstatic simplesingleton instance ()
10 {
11if (_ instance = NULL)
12 {
13 _ instance = new simplesingleton ();
14}
15 return _ instance;
16}
17}

Obviously, this implementation method is not thread-safe, and multiple simplesingleton instances may be obtained in a multi-threaded environment. To solve this problem, you can use double negation. First, create a private static variable padlock for the singleton class.

Privatestaticreadonlyobject _ padlock = newobject ();

Then modify the instance method.

1if (instance = NULL)
2 {
3 lock (_ padlock)
4 {
5if (instance = NULL)
6 {
7 instance = new Singleton ();
8}
9}
10}
11 return instance;

In practical applications, the static initialization feature of C # can be used to implement Singleton of thread security.

1 class threadsafesingleton
2 {
3 privatestatic threadsafesingleton _ instance = new threadsafesingleton ();
4
5 private threadsafesingleton ()
6 {
7}
8
9 publicstatic threadsafesingleton instance ()
10 {
11 return _ instance;
12}
13}

This method is relatively simple, but it also has a disadvantage that delayed initialization cannot be implemented. You can create a nested class in the singleton class and use the nested class to implement delayed initialization.

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.