Test Singletons Throughout The Rest of this Article, I Use Junit in Concert with log4j to test singleton classes. If you are not family, see resources.
Example 2 lists a junit test case trests example 1's singleton:
Example 2. A Singleton Test Case
import org.apache.log4j.Logger; import junit.framework.Assert; import junit.framework.TestCase; public class SingletonTest extends TestCase {private ClassicSingleton sone = null, stwo = null; private static Logger logger = Logger.getRootLogger (); Public Singletontest (String Name) {Super (Name);} public void setup () {logger.info ("getting singleleton ..."); SONE = classicsingleton.getinstance (); logger.info ("... got singleleton : " SONE); Logger.info (" getting singleton ... "); STWO = Classicsingleton.getInstance (); logger.info (" ... Got Singleton: " STWO);} public void testunique ()} Logger.info ("Checking Singletons for Equality); Assert.Assertequals (True, Sone == STWO);}}
Example 2's test case invokes ClassicSingleton.getInstance () twice and stores the returned references in member variables The testUnique () method checks to see that the references are identical Example 3 shows that test case output..:
Example 3. Test Case Output
BuildFile: build.xmlinit: [14-04-2003 03:08) Compile: Run-test-text: [java] .info main: getting starting info ... [java] info main: created Singleton: CREATED SINGETON: Singleton @ e86f41 [java] info main: ... Got Singleton: Singleton @ e86f41 [java] info main: getting singleton ... [java] info main: ... Got Singleton: Singleton @ e86f41 [java] info main: checking singletons for equality [java] Time: 0.032 [java] OK (1 test) As the preceding listing illustrates, Example 2's simple test passes with flying colors-the two singleton references obtained with ClassicSingleton.getInstance () are indeed identical; however, Those References Were Obtained in A Single Thread. The next section stress-tests Our singleton class with multiple threads.
Multithreading considerings example 1's classicsingleton.getInstance () Method is not thread-safe because of the following code:
1: IF (instance == null) {2: instance = new startload (); 3:}
If a thread is preempted at Line 2 before the assignment is made, the instance member variable will still be null, and another thread can subsequently enter the if block. In that case, two distinct singleton instances will be created. Unfortunately, that scenario rarely occurs and is therefore difficult to produce during testing to illustrate this thread Russian roulette, I've forced the issue by reimplementing Example 1's class Example 4 shows the revised singleton class..:
Example 4. Stack The Deck
import org.apache.log4j.Logger; public class Singleton {private static Singleton singleton = null; private static Logger logger = Logger.getRootLogger (); private static boolean firstThread = true; protected Singleton () {// Exists only to defeat instantiation .} public static Singleton getInstance () {if (singleton == null) {simulateRandomActivity (); singleton = new Singleton ();} logger.info ( "created singleton:" singleton); return singleton;} private static void simulateRandomActivity () {Try {if (firstthread = false; logger.info ("Sleeping ..."); // this nap shop give the second thread enough time // to get by the first thread. Thread.currentthread ( ) .sleep (50);}} catch (InterruptedException ex) {logger.warn ( "Sleep interrupted");}}} Example 4's singleton resembles Example 1's class, except the singleton in the preceding listing stacks the deck to force a multithreading error. The first time the getInstance () method is called, the thread that invoked the method sleeps for 50 milliseconds, which gives another thread time to call getInstance () and create a new singleton instance. When the sleeping thread awakes, it also creates a new singleton instance, and we have two singleton instances. Although Example 4's class is contrived, it stimulates the real-world situation where the first thread that calls getInstance () gets preempted.
Example 5 Tests Example 4's Singleton:
Example 5. a Test Test Test That Fails
import org.apache.log4j.Logger; import junit.framework.Assert; import junit.framework.TestCase; public class SingletonTest extends TestCase {private static Logger logger = Logger.getRootLogger (); private static Singleton singleton = null; public SingletonTest ( String name) {super (name);} public void setUp () {singleton = null;}. public void testUnique () throws InterruptedException {// Both threads call Singleton.getInstance () Thread threadOne = new Thread (new SingletonTestRunnable () ), threadTwo = new Thread (new SingletonTestRunnable ()); threadOne.start (); threadTwo.start (); threadOne.join (); threadTwo.join ();} private static class SingletonTestRunnable implements Runnable {public void run () {// Get a reason to the Singleton. Singleton S = Singleton.GetInstance (); // Protect Singleton Member Variable from // Multithreaded Access. Synchronized (Singletontest.class) { IF (Singleton == NULL) // if Local Reference Is Null ... Singleton = S; // ... set it to the singleleton} // local reference must be equal to the one and // only instance of singleton; Otherwise, we have two // singleton instances. Assert.assertequals (true, s == singleton);}}}
Example 5's test case creates two threads, starts each one, and waits for them to finish. The test case maintains a static reference to a singleton instance, and each thread calls Singleton.getInstance (). If the static member variable has not been set , the first thread sets it to the singleton obtained with the call to getInstance (), and the static member variable is compared to the local variable for equality.Here's what happens when the test case runs: The first thread calls getInstance (), enters the if block, and sleeps. Subsequently, the second thread also calls getInstance () and creates a singleton instance. The second thread then sets the static member variable to the instance it created. The second thread checks the static member variable and the local copy for equality, and the test passes. When the first thread awakes, it also creates a singleton instance, but that thread does not set the static member variable (because the second thread has already set it), so the static vari Able and the local variable area out of synch, and the test for equality fails. EXAMPLE 6 LISTS EXAMPLE 5'S TEST CASE OUTPUT:
Example 6. EXAMPLE 5'S OUTPUT
Buildfile: build.xmlinit: [Echo] Build 20030414 (14-04-2003 03:06) Compile: Run-test-text: info thread-1: sleeping ... Info Thread-2: Created Singleton: Singleton @ 7e5cbdinfo thread -1: Created Singleton: Singleton@704ebbjunit.framework.assertionFaileDerror: Expected:
But WAS:
At junit.framework.assert.fail (askERT.JAVA: 47)
At junit.framework.assert.failnotequals (askERT.JAVA: 282)
At junit.framework.assert.assertequals (askERT.JAVA: 64)
At junit.framework.assert.assertequals (askERT.JAVA:149)
At junit.framework.assert.assertequals (assert.java:155)
At singletontest $ singletontestrunnable.run (unknown Source) at java.lang.thread.run (thread.java: 554)
[java].
[java] Time: 0.577
[java] OK (1 test)
Now That We know Example 4's Singleton Is Not Thread-Safe, Let's See How We CAN FIX IT.
Synchronization Making Example 4's Singleton Class Thread-Safe Is Easy-Just Synchronize The getInstance () Method Like this:
Public synchronized static singleton getinstance () {if (Singleton == Null) {simulaterAndomactivity (); singleton = new singleleton ();} logger.info ("Created Singleton;}; return
After We synchronize the getInstance () Method, We can Run Example 5's Test Case with The Following Results:
BuildFile: Build.xmlinit: [Echo] Build 20030414 (14-04-2003 03:15) Compile: [Javac] Compiling 2 Source Filesrun-Test-Text: Info Thread-1: Sleeping ... Info Thread-1: Created Singleton: Singleton @ EF577DINFO THREAD-2: Created Singleton: Singleton @ EF577D [Java]. [Java] Time: 0.513 [Java] OK (1 Test)
This time, the test case works and our multithreading worries are over; however, the astute reader may realize that the getInstance method only needs to be synchronized the first time it is called Because synchronization is very expensive performance-wise (synchronized methods (). Can Run Up to 100 Times Slower Than Unsynchronized Methods, Perhaps We CAN Introduce A Performance Enhancement That Only Synchronizes The Singleton Assignment In getInstance ().
A Performance Enhancement in Search of a Performance Enhancement, you might choose to shutrite the getInstance () Method Like this:
public static Singleton getInstance () {if (singleton == null) {synchronized (Singleton.class) {singleton = new Singleton ();}} return singleton;} Instead of synchronizing the entire method, the preceding code fragment only synchronizes the critical . code However, the preceding code fragment is not thread-safe Consider the following scenario:. Thread 1 enters the synchronized block, and, before it can assign the singleton member variable, the thread is preempted Subsequently, another thread can enter the if. Block. The Second Thread Will Wait for The First Thread To Finish, But We Will Still WIND UP WITH TWO DISTINCT SINGETON INSTANCES. Is The There a Way To Fix This Problem? Read on.
Double-checked locking Double-checked locking is a technique that, at first glance, appears to make lazy instantiation thread-safe That technique is illustrated in the following code fragment.:
Public static singleleton getInstance () {if (Singleton == null) {singleton == null) {singleton = new singleleton ();}}}} return singleton;
What happens if two threads simultaneously access getInstance ()? Imagine Thread 1 enters the synchronized block and is preempted. Subsequently, a second thread enters the if block. When Thread 1 exits the synchronized block, Thread 2 makes a second check to see if the Singleton Instance Is Still Null. Since Thread 1 Set The Singleton Member Variable, Thread 2'S Second Check Will Fail, And A Second Singleton Will Not Be CREATED. OR SO IT SEEMS.
Unfortunately, double-checked locking is not guaranteed to work because the compiler is free to assign a value to the singleton member variable before the singleton's constructor is called. If that happens, Thread 1 can be preempted after the singleton reference has been assigned, but before the singleton is initialized, so Thread 2 can return a reference to an uninitialized singleton instance.Since double-checked locking is not guaranteed to work, you must synchronize the entire getInstance () method. However, another alternative is simple, fast, and Thread-Safe.
AN Alternative Thread-Safe Singleton Implementation Example 7 Lists A Simple, Fast, and Thread-Safe Singleton Implementation:
Example 7. a Simple Singleton
Public class singleton {public final static singleleton instance = new singleleton (); private singleton () {// exists only to defeat instantiation.}
The preceding singleton implementation is thread-safe because static member variables created when declared are guaranteed to be created the first time they are accessed You get a thread-safe implementation that automatically employs lazy instantiation; here's how you use it.:
Singleton Singleton = Singleton.Instance; Singleton.doth (); Singleton.dothat (); ...
Of course, like nearly everything else, the preceding singleton is a compromise; if you use that implementation, you can not change your mind and allow multiple singleton instances later on With a more conservative singleton implementation, instances are obtained through a getInstance (. ) Method, And You Chan Change Those Methods To Return A Unique Instance OR One of Hundreds. You can't do the Same with a public static member variable.