Thread Safe Singleton using Eager Loading

Eager loading is a technique used in the Singleton design pattern to ensure that a singleton instance is created at the time of application startup. This can be useful in scenarios where the singleton instance is needed immediately, or where initialization is resource-intensive and should be done upfront.

The advantage of using "Eager Loading in the Singleton Design Pattern" is that the CLR (Common Language Runtime) will take care of Object Initialization and Thread Safety in Multithread Environment, means we will not be required to write any code explicitly for handling the thread safety for a multithreaded environment.

Here’s a simple example of how to implement an eager-loaded Singleton in C#:

Eager Loading Singleton Example

using System;

public class EagerSingleton
{
    // Step 1: Create a private static instance of the class
    //Initializing the Variable at the time of class start-up.
    private static readonly EagerSingleton _instance = new EagerSingleton();

    // Step 2: Private constructor to prevent instantiation from outside.
    private EagerSingleton()
    {
        // Initialize your instance here.
        Console.WriteLine("EagerSingleton instance created.");
    }

    // Step 3: Provide a public static method to access the instance.
    public static EagerSingleton Instance
    {
        //No need to write separate code for NULL checking.
        //Here Object initialization and Thread-Safety will be taken care by CLR.
        get
        {
            return _instance;
        }
    }

    // Example method to demonstrate functionality
    public void DoSomething()
    {
        Console.WriteLine("Doing something with the EagerSingleton instance.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Access the Singleton instance
        EagerSingleton eagerSingleton = EagerSingleton.Instance;
        singleton.DoSomething();

        // Try to get another instance
        EagerSingleton anotherEagerSingleton = EagerSingleton.Instance;
        Console.WriteLine($"Are both the instances same ? { eagerSingleton == anotherEagerSingleton }");
    }
}

Output

When you run the above program, you will see the following output:



EagerSingleton instance created.
Doing something with the EagerSingleton instance.
Are both instances the same? True


Explanation:

  • Static Instance: The instance of EagerSingleton is created and assigned to a static readonly field _instance when the class is loaded.

  • Private Constructor: The constructor remains private to prevent instantiation from outside.

  • Instance Property: The Instance property simply returns the already created instance.

  • Usage: In the Main method, you can access the singleton instance and invoke its methods.


When to Use Eager Loading ?

  • Guaranteed Usage: Use eager loading - when you are sure that the singleton instance will be needed during the application lifecycle.

  • Simple Initialization: It is suitable when the initialization logic is simple and doesn't involve heavy resource allocation.

  • Thread Safety Not an Issue: Since the instance is created at class loading time, concerns about thread safety are eliminated.


Conclusion

Eager loading can be a straightforward and effective way to implement the singleton pattern, particularly when you want to ensure that the instance is ready for use as soon as the application starts.

However, be mindful of memory usage, especially if the singleton instance is large or if it may not be used throughout the application's lifecycle.