Java : Creating a Singleton class and using Asserts for Verification


  • This sample instantiates a  Singleton class with Eager Initialization
  • Demonstrates using  asserts to compare objects and strings

Java Sources
package hhu;
public class Singleton 
    public final long itime;
    private static volatile Singleton singletonInstance = new Singleton();     
     //  Making constructor as private to prevent access to outsiders
     //  The instance of Singleton()  is created at the startup of the class. 
     //  Since it’s a static, it gets loaded and created during loading of the UCP class.
    private Singleton() 
            // save the object instantiation time 
      itime = System.currentTimeMillis(); 
      System.out.println("Singleton() Constructor called ");
    public static Singleton getInstance() 
    return singletonInstance;
package hhu;    
import static org.testng.Assert.assertEquals;
public class SingletonTest
    public static void main(String[] args) throws Exception
        System.out.println("SingletonTest () invoked !");
        Singleton instance1 = Singleton.getInstance();
            // As we compare the obect instantiation time -  a short sleep 
            // should return a different itime if we have no singleton object !
        Singleton instance2 = Singleton .getInstance();
        System.out.println("Checking singleton objects equality");
        assertEquals(instance1,instance2, "Objects are NOT equal !");
        System.out.println("Our UCP classes are equal: " + 
               "- instance2.itime: "  + instance1.itime    + 
               " - instance2.itime: "  + instance2.itime );
        System.out.println("Testing  string equality - No assertion expected");
        String s1 = "s1";
        String s2 = "s1";
        assertEquals(s1,s2, "Strings are NOT equal !");
        System.out.println("Here we are - strings are equal : s1 == s2");
        System.out.println("Testing  string equality - now firing java.lang.AssertionError");
        s2 = s2 + "s2";
        assertEquals(s1,s2, "String Objects are NOT equal - Assertion !");
        System.out.println("This line will be never reached");      

Run SingletonTest

SingletonTest () invoked !
Singleton() Constructor called 
Checking singleton objects equality
Our UCP classes are equal: - instance2.itime: 1426087941252 - instance2.itime: 1426087941252
Testing  string equality - No assertion expected
Here we are - strings are equal : s1 == s2
Testing  string equality - now firing java.lang.AssertionError
Exception in thread "main" java.lang.AssertionError: String Objects are NOT equal - 
    Assertion ! expected [s1s2] but found [s1]
    at org.testng.Assert.failNotEquals(
    at org.testng.Assert.assertEquals(
    at org.testng.Assert.assertEquals(
    at hhu.SingletonTest.main(
Java Result: 1


Leave a Reply

Your email address will not be published. Required fields are marked *