Make Singleton Class Thread-Safe

Singleton Design Pattern ensures that Only One Instance is created.  But, It will impose challenges in the Multi-threaded scenarios.

  • Multiple Thread causes Issues If entering the GetInstance() method
  • We need to use Lock keyword to ensure only 1 Thread enters the Instance Creation
  • We need to add additional check on Instance is Null inside the lock statement

public class ConnectionPool

{
private static ConnectionPool instance;
private static object _lockObject = new object();

public static ConnectionPool GetInstance()
{
if (instance == null)
{
lock (_lockObject)
{
if (instance != null)
instance = new ConnectionPool();
}
}

return instance;
}

private ConnectionPool()
{
// doesn’t matter what’s here
}

}

Reference

I have written a book Design Patterns in C# few years back.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s