1 7 8 package org.dom4j.util; 9 10 import junit.framework.Test; 11 import junit.framework.TestSuite; 12 import junit.framework.TestCase; 13 import junit.extensions.RepeatedTest; 14 15 import java.util.HashMap ; 16 import java.util.Map ; 17 18 import com.clarkware.junitperf.LoadTest; 19 import com.clarkware.junitperf.TimedTest; 20 21 33 public class PerThreadSingletonTest extends TestCase { 34 public PerThreadSingletonTest(String name) { 35 super(name); 36 } 37 38 private static SingletonStrategy singleton; 39 40 private static ThreadLocal reference = new ThreadLocal (); 41 42 public void setUp() throws Exception { 43 super.setUp(); 44 synchronized (PerThreadSingletonTest.class) { 45 if (singleton == null) { 46 singleton = new PerThreadSingleton(); 47 singleton.setSingletonClassName(HashMap .class.getName()); 48 } 49 } 50 } 51 52 public void tearDown() throws Exception { 53 super.tearDown(); 54 } 55 56 public void testInstance() throws Exception { 57 String tid = Thread.currentThread().getName(); 58 Map map = (Map ) singleton.instance(); 59 60 String expected = "new value"; 61 if (!map.containsKey(tid) && reference.get() != null) { 62 System.out.println("tid=" + tid + " map=" + map); 63 System.out.println("reference=" + reference); 64 System.out.println("singleton=" + singleton); 65 fail("created singleton more than once"); 66 } else { 67 map.put(tid, expected); 68 reference.set(map); 69 } 70 71 String actual = (String ) map.get(tid); 72 assertEquals("testInstance", expected, actual); 74 75 map = (Map ) singleton.instance(); 76 expected = "new value"; 77 actual = (String ) map.get(tid); 78 assertEquals("testInstance", expected, actual); 82 assertEquals("testInstance reference", reference.get(), map); 83 84 } 85 86 91 public static Test suite() { 92 TestSuite suite = new TestSuite(); 93 suite.addTest(makeRepeatedLoadTest(5, 100, "testInstance")); 94 return suite; 95 } 96 97 109 protected static Test makeRepeatedLoadTest(int users, int iterations, 110 String testMethod) { 111 long maxElapsedTime = 1200 + (1000 * users * iterations); 112 113 Test testCase = new PerThreadSingletonTest(testMethod); 114 115 Test repeatedTest = new RepeatedTest(testCase, iterations); 116 Test loadTest = new LoadTest(repeatedTest, users); 117 Test timedTest = new TimedTest(loadTest, maxElapsedTime); 118 119 return timedTest; 120 } 121 } 122 123 159 160 | Popular Tags |