Skip to content

Commit 2baad7a

Browse files
authored
doc for thread safe singleton
1 parent 77bf9eb commit 2baad7a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

CreationalPatterns/Singleton/README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,5 +38,40 @@ Because the **Singleton** instance is referenced by a private static member vari
3838
* you want to keep separate threads from creating new instances of the singleton at the same time (thread-safe)
3939
* you want to create an instance only when the instance is needed.
4040

41+
[ChocolateBoiler_ThreadSafe.cs](/CreationalPatterns/Singleton/ChocolateBoiler_ThreadSafe.cs).
42+
```cs
43+
public sealed class ChocolateBuilder_ThreadSafe
44+
{
45+
// singleton instance
46+
// the volatile keyword ensures that multiple threads handle the singleton instance variable correctly
47+
private static volatile ChocolateBuilder_ThreadSafe instance;
48+
private static object syncLock = new object();
49+
50+
public static ChocolateBuilder_ThreadSafe Instance
51+
{
52+
get
53+
{
54+
// Check for an instance and if there isn't one, enter a locked block
55+
if (instance == null)
56+
{
57+
lock (syncLock)
58+
{
59+
// Once in the block, check again and if still null
60+
if(instance == null)
61+
{
62+
instance = new ChocolateBuilder_ThreadSafe();
63+
}
64+
}
65+
}
66+
return instance;
67+
}
68+
}
69+
}
70+
```
71+
The singleton instance is declared to be **volatile** to ensure that assignment to the instance variable completes before the instance variable can be accessed.
72+
Lastly, this approach uses a **syncRoot** instance to lock on, rather than locking on the type itself, to avoid deadlocks.
73+
74+
This double-checked locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the instance propery method. It also allows you to delay instantiation until the object is first accessed.
75+
4176
Reference:
4277
* MSDN - [Implementing Singleton in C#](https://msdn.microsoft.com/en-us/library/ff650316.aspx)

0 commit comments

Comments
 (0)