singleton and thread safe for load balancer

http://www.codeproject.com/Articles/37976/Writing-Thread-Safe-Code-in-C

Using the code

ServerLoadBalancerEngine implements the Singleton pattern and here we need to ensure that multiple thread calls to GetServerLoadBalancerEngine should be synchronized.

The static object syncLock is used to implement a critical section in the GetServerLoadBalancerEngine function.

To synchronise static methods, we need to lock the private static object variable. Locking GetServerLoadBalancerEngine ensures that only one thread can operate on this method, so only one instance will be created of the ServerLoadBalancerEngine class.

Collapse | Copy Code
sealed class ServerLoadBalancerEngine
{
    private static ServerLoadBalancerEngine _instance;
    private List<Server> _servers;
    private Random _random = new Random();

    // syncLock object, used to lock the code block
    private static object syncLock = new object();

    // constructor is 'private'
    private ServerLoadBalancerEngine()
    {

        // Load list of available servers
        _servers = new List<Server>
        {
            new Server{ Name = "Server1", IPAddress = "120.14.220.18" },
            new Server{ Name = "Server2", IPAddress = "120.14.220.19" },
            new Server{ Name = "Server3", IPAddress = "120.14.220.20" },
            new Server{ Name = "Server4", IPAddress = "120.14.220.21" }, 
        };
    }

    public static ServerLoadBalancerEngine GetServerLoadBalancerEngine()
    {
        if (_instance == null)
        {
            //To ensure thread safety
            lock (syncLock)
            {
                if (_instance == null)
                {
                    _instance = new ServerLoadBalancerEngine();
                }
            }
        }
        return _instance;
    }

    // Simple, but effective load balancer
    public Server NextServer
    {
        get
        {
            int r = _random.Next(_servers.Count);
            return _servers[r];
        }
    }
}
Advertisements

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