All about multithreading.

Thursday, August 30, 2007

Multithreaded Singleton: Double-check locking

The following code ensures,

  1. Only one thread can enter the critical area (lock statement)
  2. Only one instance is created and only when the instance is needed (get accessor)
  3. The variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.
  4. This uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks.
  5. Double-check locking solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method.

The first check avoids an exclusive lock in every call to the Instance property method.
The second check ensures that instance is created only once. Without the second check, check the following scenario.

Thread 1 locks synRoot 
Thread 1 started initializing singleton object.
Thread 2 enters and waits at lock syncroot
Thread 1 finishes the initialization of singleton object and exits.
Thread 2 enters and starts another initialization!

using System;

public sealed class Singleton
{
    private static volatile Singleton instance;
    private static object syncRoot = new Object();

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {

            // First check
            if (instance == null)
            {
                lock (syncRoot)
                {
                    // Second check
                    if (instance == null)
                        instance = new Singleton();
                }
            }

            return instance;
        }
    }
}

More at http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

2 comments:

Harsha said...

Hello Srikantha,

Its really a very nice thought of coming up with writing a blog to register your finding on Multi threading in .Net and C#. Thanks to your friend who inspired you to do this.

Expecting more articles on Multithreading.

Thanks
Harsha

Tran Quoc Bao said...

Thank you very much. It is very good sample.

Blog Archive

About Me

One of my friends said "if you want to learn something, write a book about it". I wanted to learn all about multithreading and instead of writing a book, I am trying to blog. Thank you for stopping. I appreciate your feedback. Sreekanth