w3resource

Testing Java Singleton class for Multi-Threading with JUnit


9. Test Singleton in Multi-threaded Context

Write a Java program that tests a singleton class, ensuring it behaves as expected in a multi-threaded environment.

Sample Solution:

Java Code:

// Singleton.java
public class Singleton {

    private static volatile Singleton instance;

    private Singleton() {
        // Private constructor to prevent instantiation
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

// SingletonTest.java

import org.junit.Test;

import static org.junit.Assert.assertEquals;


public class SingletonTest {

    @Test
    public void testSingletonInstance() throws InterruptedException {
        // Create multiple threads to access the singleton instance concurrently
        Thread thread1 = new Thread(() -> {
            Singleton instance1 = Singleton.getInstance();
            try {
                Thread.sleep(100); // Simulate some work in the thread
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Singleton instance2 = Singleton.getInstance();

            // Assert that both instances obtained in the same thread are the same
            assertEquals(instance1, instance2);
        });

        Thread thread2 = new Thread(() -> {
            Singleton instance3 = Singleton.getInstance();
            try {
                Thread.sleep(100); // Simulate some work in the thread
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Singleton instance4 = Singleton.getInstance();

            // Assert that both instances obtained in the same thread are the same
            assertEquals(instance3, instance4);
        });

        // Start the threads
        thread1.start();
        thread2.start();

        // Wait for threads to finish
        thread1.join();
        thread2.join();
    }

    public static void main(String[] args) {
        // Run the JUnit test
        org.junit.runner.JUnitCore.main("SingletonTest");
    }
}

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:

Flowchart: Testing Java Singleton class for Multi-Threading with JUnit
Flowchart: Testing Java Singleton class for Multi-Threading with JUnit

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.

Go to:


PREV : Test Private Methods.
NEXT : Test Component Interactions.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.