1 16 17 package org.springframework.beans.factory; 18 19 import java.text.ParseException ; 20 import java.text.SimpleDateFormat ; 21 import java.util.Collections ; 22 import java.util.Date ; 23 import java.util.HashSet ; 24 import java.util.Set ; 25 26 import junit.framework.TestCase; 27 import org.apache.commons.logging.Log; 28 import org.apache.commons.logging.LogFactory; 29 30 import org.springframework.beans.factory.xml.XmlBeanFactory; 31 import org.springframework.beans.propertyeditors.CustomDateEditor; 32 import org.springframework.core.io.ClassPathResource; 33 34 39 public class ConcurrentBeanFactoryTests extends TestCase { 40 41 private static final Log logger = LogFactory.getLog(ConcurrentBeanFactoryTests.class); 42 43 private static final SimpleDateFormat df = new SimpleDateFormat ("yyyy/MM/dd"); 44 45 private static final Date date1; 46 47 private static final Date date2; 48 49 static { 50 try { 51 date1 = df.parse("2004/08/08"); 52 date2 = df.parse("2000/02/02"); 53 } 54 catch (ParseException e) { 55 throw new RuntimeException (e); 56 } 57 } 58 59 private BeanFactory factory; 60 61 private Set set = Collections.synchronizedSet(new HashSet ()); 62 63 private Throwable ex = null; 64 65 protected void setUp() throws Exception { 66 XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("concurrent.xml", getClass())); 67 CustomDateEditor editor = new CustomDateEditor(df, false); 68 factory.registerCustomEditor(Date .class, editor); 69 this.factory = factory; 70 } 71 72 public void testSingleThread() { 73 for (int i = 0; i < 100; i++) { 74 performTest(); 75 } 76 } 77 78 public void testConcurrent() { 79 for (int i = 0; i < 30; i++) { 80 TestRun run = new TestRun(); 81 set.add(run); 82 Thread t = new Thread (run); 83 t.setDaemon(true); 84 t.start(); 85 } 86 logger.info("Thread creation over, " + set.size() + " still active."); 87 synchronized (set) { 88 while (!set.isEmpty() && ex == null) { 89 try { 90 set.wait(); 91 } 92 catch (InterruptedException e) { 93 logger.info(e.toString()); 94 } 95 logger.info(set.size() + " threads still active."); 96 } 97 } 98 if (ex != null) { 99 fail(ex.getMessage()); 100 } 101 } 102 103 private void performTest() { 104 ConcurrentBean b1 = (ConcurrentBean) factory.getBean("bean1"); 105 ConcurrentBean b2 = (ConcurrentBean) factory.getBean("bean2"); 106 107 assertEquals(b1.getDate(), date1); 108 assertEquals(b2.getDate(), date2); 109 } 110 111 112 private class TestRun implements Runnable { 113 114 public void run() { 115 try { 116 for (int i = 0; i < 100; i++) { 117 performTest(); 118 } 119 } 120 catch (Throwable e) { 121 ex = e; 122 } 123 finally { 124 synchronized (set) { 125 set.remove(this); 126 set.notifyAll(); 127 } 128 } 129 } 130 } 131 132 133 public static class ConcurrentBean { 134 135 private Date date; 136 137 public Date getDate() { 138 return date; 139 } 140 141 public void setDate(Date date) { 142 this.date = date; 143 } 144 } 145 146 } 147 | Popular Tags |