Testing Java Singleton class for Multi-Threading with JUnit
Write a Java program that tests a singleton class, ensuring it behaves as expected in a multi-threaded environment.
Sample Solution:
Java Code:
Sample Output:
JUnit version 4.10 . Time: 0.114 OK (1 test)
Explanation:
The above exercise code consists of two Java classes:
- Singleton.java
- This class represents a singleton pattern implementation using double-check locking to ensure thread safety during lazy initialization.
- The class has a private static volatile instance variable, which is the single instance of the class.
- The constructor is private to prevent external instantiation.
- The "getInstance()" method is a static method that returns the singleton instance. It uses double-check locking to ensure that only one instance is created, even in a multi-threaded environment.
- SingletonTest.java:
- This class contains a JUnit test to verify the behavior of the "Singleton" class in a multi-threaded environment.
- The "testSingletonInstance()" method creates two threads, each trying to obtain the singleton instance concurrently.
- In each thread, it asserts that the instances obtained before and after a short sleep are the same, ensuring thread safety.
- The "main" method is provided for running the JUnit test using "JUnitCore".
Flowchart:


For more Practice: Solve these Related Problems:
- Write a Java program to create a test case that validates a singleton instance remains unique when accessed concurrently by multiple threads.
- Write a Java program to implement a test case that simulates race conditions and verifies that the singleton pattern is maintained.
- Write a Java program to design a test case using concurrent threads to call getInstance() and assert all returned instances are the same.
- Write a Java program to construct a test case that stresses a singleton class with high parallelism to confirm thread safety.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Java Testing Private methods with reflection: ExampleClass demonstration.
Next: Java Application Integration testing with JUnit: UserService and OrderService Interaction.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics