Merge pull request #263 from iamrichardjones/master

Update to singleton unit tests and lazy loading unit test
This commit is contained in:
Ilkka Seppälä 2015-10-19 21:21:45 +03:00
commit 8eff279233
3 changed files with 110 additions and 61 deletions

View File

@ -0,0 +1,42 @@
package com.iluwatar.lazy.loading;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* Using reflection this test shows that the heavy field is not instantiated until the method getHeavy is called
*
* Created by jones on 11/10/2015.
*/
public class HolderThreadSafeTest {
@Test
public void test() throws IllegalAccessException {
HolderThreadSafe hts = new HolderThreadSafe();
{//first call is null
Field[] ff = HolderThreadSafe.class.getDeclaredFields();
for (Field f: ff) {
f.setAccessible(true);
}
assertNull(ff[0].get(hts));
}
// now it is lazily loaded
hts.getHeavy();
{//now it is not null - call via reflection so that the test is the same before and after
Field[] ff = HolderThreadSafe.class.getDeclaredFields();
for (Field f: ff) {
f.setAccessible(true);
}
assertNotNull(ff[0].get(hts));
}
}
}

View File

@ -4,6 +4,8 @@ package com.iluwatar.singleton;
* Thread-safe Singleton class. * Thread-safe Singleton class.
* The instance is lazily initialized and thus needs synchronization * The instance is lazily initialized and thus needs synchronization
* mechanism. * mechanism.
*
* Note: if created by reflection then a singleton will not be created but multiple options in the same classloader
*/ */
public class ThreadSafeLazyLoadedIvoryTower { public class ThreadSafeLazyLoadedIvoryTower {

View File

@ -2,73 +2,78 @@ package com.iluwatar.singleton;
import org.junit.Test; import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import static org.junit.Assert.assertEquals;
/** /**
* This class provides several test case that test singleton construction.
* *
* This test case demonstrates thread safety issues of lazy loaded Singleton implementation. * The first proves that multiple calls to the singleton getInstance object are the same when called in the SAME thread.
* <p> * The second proves that multiple calls to the singleton getInstance object are the same when called in the DIFFERENT thread.
* Out of the box you should see the test output something like the following:
* <p>
* Thread=Thread-4 got instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@6fde356e
* Thread=Thread-2 creating instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@6fde356e
* Thread=Thread-0 creating instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@6fde356e
* Thread=Thread-0 got instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@6fde356e
* Thread=Thread-3 got instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@6fde356e
* Thread=Thread-1 got instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@60f330b0
* Thread=Thread-2 got instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@6fde356e
* <p>
* By changing the method signature of LazyLoadedIvoryTower#getInstance from
* <p><blockquote><pre>
* public static LazyLoadedIvoryTower getInstance()
* </pre></blockquote><p>
* into
* <p><blockquote><pre>
* public synchronized static LazyLoadedIvoryTower getInstance()
* </pre></blockquote><p>
* you should see the test output change to something like the following:
* <p>
* Thread=Thread-4 creating instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@3c688490
* Thread=Thread-4 got instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@3c688490
* Thread=Thread-0 got instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@3c688490
* Thread=Thread-3 got instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@3c688490
* Thread=Thread-2 got instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@3c688490
* Thread=Thread-1 got instance=com.iluwatar.singleton.LazyLoadedSingletonThreadSafetyTest$LazyLoadedIvoryTower@3c688490
* *
*/ */
public class LazyLoadedSingletonThreadSafetyTest { public class LazyLoadedSingletonThreadSafetyTest {
private static final int NUM_THREADS = 5; private static final int NUM_THREADS = 5;
private List<ThreadSafeLazyLoadedIvoryTower> threadObjects = Collections.synchronizedList(new ArrayList<>());
//NullObject class so Callable has to return something
private class NullObject{private NullObject(){}}
@Test @Test
public void test() { public void test_MultipleCallsReturnTheSameObjectInSameThread() {
SingletonThread runnable = new SingletonThread(); //Create several instances in the same calling thread
for (int j=0; j<NUM_THREADS; j++) { ThreadSafeLazyLoadedIvoryTower instance1 = ThreadSafeLazyLoadedIvoryTower.getInstance();
Thread thread = new Thread(runnable); ThreadSafeLazyLoadedIvoryTower instance2 = ThreadSafeLazyLoadedIvoryTower.getInstance();
thread.start(); ThreadSafeLazyLoadedIvoryTower instance3 = ThreadSafeLazyLoadedIvoryTower.getInstance();
//now check they are equal
assertEquals(instance1, instance1);
assertEquals(instance1, instance2);
assertEquals(instance2, instance3);
assertEquals(instance1, instance3);
}
@Test
public void test_MultipleCallsReturnTheSameObjectInDifferentThreads() throws InterruptedException, ExecutionException {
{//create several threads and inside each callable instantiate the singleton class
ExecutorService executorService = Executors.newSingleThreadExecutor();
List<Callable<NullObject>> threadList = new ArrayList<>();
for (int i = 0; i < NUM_THREADS; i++) {
threadList.add(new SingletonCreatingThread());
}
ExecutorService service = Executors.newCachedThreadPool();
List<Future<NullObject>> results = service.invokeAll(threadList);
//wait for all of the threads to complete
for (Future res : results) {
res.get();
}
//tidy up the executor
executorService.shutdown();
}
{//now check the contents that were added to threadObjects by each thread
assertEquals(NUM_THREADS, threadObjects.size());
assertEquals(threadObjects.get(0), threadObjects.get(1));
assertEquals(threadObjects.get(1), threadObjects.get(2));
assertEquals(threadObjects.get(2), threadObjects.get(3));
assertEquals(threadObjects.get(3), threadObjects.get(4));
} }
} }
private static class SingletonThread implements Runnable { private class SingletonCreatingThread implements Callable<NullObject> {
@Override @Override
public void run() { public NullObject call() {
LazyLoadedIvoryTower instance = LazyLoadedIvoryTower.getInstance(); //instantiate the thread safety class and add to list to test afterwards
System.out.println("Thread=" + Thread.currentThread().getName() + " got instance=" + instance); ThreadSafeLazyLoadedIvoryTower instance = ThreadSafeLazyLoadedIvoryTower.getInstance();
} threadObjects.add(instance);
} return new NullObject();//return null object (cannot return Void)
private static class LazyLoadedIvoryTower {
private static LazyLoadedIvoryTower instance = null;
private LazyLoadedIvoryTower() {
}
public static LazyLoadedIvoryTower getInstance() {
if (instance == null) {
instance = new LazyLoadedIvoryTower();
System.out.println("Thread=" + Thread.currentThread().getName() + " creating instance=" + instance);
}
return instance;
} }
} }
} }