Tutorialspoint
Problem
Solution
Submissions

Thread-Safe Singleton Implementation

Certification: Intermediate Level Accuracy: 66.67% Submissions: 3 Points: 15

Write a C# program to implement a thread-safe singleton class. A singleton is a design pattern that restricts the instantiation of a class to only one instance and provides a global point of access to it.

Example 1
  • Input:
    • Logger logger1 = Logger.Instance;
    • logger1.Log("Message from thread 1");
    • Logger logger2 = Logger.Instance;
    • logger2.Log("Message from thread 2");
    • Console.WriteLine(object.ReferenceEquals(logger1, logger2));
  • Output:
    • Initializing Logger instance...
    • Message from thread 1
    • Message from thread 2
    • True
  • Explanation:
    • Step 1: First access to Logger.Instance creates a new instance, showing initialization message.
    • Step 2: The first logger instance logs a message from thread 1.
    • Step 3: Second access to Logger.Instance returns the existing instance (no initialization message).
    • Step 4: The second logger instance logs a message from thread 2.
    • Step 5: ReferenceEquals confirms both variables reference the same object, proving singleton behavior.
Example 2
  • Input:
    • Task[] tasks = new Task[5];
    • for (int i = 0; i < tasks.Length; i++)
    • {
    • int threadId = i;
    • tasks[i] = Task.Run(() => {
    • Logger logger = Logger.Instance;
    • logger.Log($"Message from thread {threadId}");
    • });
    • }
    • Task.WaitAll(tasks);
  • Output:
    • Initializing Logger instance...
    • Message from thread 0
    • Message from thread 1
    • Message from thread 2
    • Message from thread 3
    • Message from thread 4
  • Explanation:
    • Step 1: Create 5 parallel tasks, each accessing the Logger singleton.
    • Step 2: Only one initialization message appears, confirming the singleton is only initialized once.
    • Step 3: All tasks successfully access the same singleton instance to log their messages.
    • Step 4: Thread synchronization ensures no race conditions occur during initialization.
    • Step 5: All messages are properly logged from the 5 different threads using the same instance.
Constraints
  • Must be thread-safe under heavy concurrent access
  • Initialization should happen only once
  • Instance access time should be O(1) after initialization
  • Space Complexity: O(1) as only one instance exists
  • Must handle reentrant calls and avoid deadlocks
NumberGoogleFacebook
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Consider using lazy initialization with the `Lazy` class
  • Alternatively, implement double-checked locking for efficiency
  • You can also use a static constructor for thread safety
  • Ensure proper access modifiers to prevent direct instantiation
  • Consider implementing IDisposable if your singleton manages resources

Steps to solve by this approach:

 Step 1: Declare a private static field using Lazy to hold the singleton instance.
 Step 2: Make the constructor private to prevent direct instantiation.
 Step 3: Create a public static property that provides access to the singleton instance.
 Step 4: Use the thread-safe Lazy initialization to ensure only one instance is created.
 Step 5: Implement application-specific functionality in the singleton class.

Submitted Code :