
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
Editorial
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. | ||||
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