1 16 17 package org.springframework.beans; 18 19 import java.io.ByteArrayOutputStream ; 20 import java.io.IOException ; 21 import java.util.Collections ; 22 import java.util.HashSet ; 23 import java.util.Iterator ; 24 import java.util.Properties ; 25 import java.util.Set ; 26 27 import junit.framework.TestCase; 28 import org.apache.commons.logging.Log; 29 import org.apache.commons.logging.LogFactory; 30 31 36 public class ConcurrentBeanWrapperTests extends TestCase { 37 38 private final Log logger = LogFactory.getLog(getClass()); 39 40 private Set set = Collections.synchronizedSet(new HashSet ()); 41 42 private Throwable ex = null; 43 44 public void testSingleThread() { 45 for (int i = 0; i < 100; i++) { 46 performSet(); 47 } 48 } 49 50 public void testConcurrent() { 51 for (int i = 0; i < 10; i++) { 52 TestRun run = new TestRun(this); 53 set.add(run); 54 Thread t = new Thread (run); 55 t.setDaemon(true); 56 t.start(); 57 } 58 logger.info("Thread creation over, " + set.size() + " still active."); 59 synchronized (this) { 60 while (!set.isEmpty() && ex == null) { 61 try { 62 wait(); 63 } 64 catch (InterruptedException e) { 65 logger.info(e.toString()); 66 } 67 logger.info(set.size() + " threads still active."); 68 } 69 } 70 if (ex != null) { 71 fail(ex.getMessage()); 72 } 73 } 74 75 private static void performSet() { 76 TestBean bean = new TestBean(); 77 78 Properties p = (Properties ) System.getProperties().clone(); 79 80 assertTrue("The System properties must not be empty", p.size() != 0); 81 82 for (Iterator i = p.entrySet().iterator(); i.hasNext();) { 83 i.next(); 84 if (Math.random() > 0.9) { 85 i.remove(); 86 } 87 } 88 89 ByteArrayOutputStream buffer = new ByteArrayOutputStream (); 90 try { 91 p.store(buffer, null); 92 } 93 catch (IOException e) { 94 } 97 String value = new String (buffer.toByteArray()); 98 99 BeanWrapperImpl wrapper = new BeanWrapperImpl(bean); 100 wrapper.setPropertyValue("properties", value); 101 assertEquals(p, bean.getProperties()); 102 } 103 104 105 private static class TestRun implements Runnable { 106 107 private ConcurrentBeanWrapperTests test; 108 109 public TestRun(ConcurrentBeanWrapperTests test) { 110 this.test = test; 111 } 112 113 public void run() { 114 try { 115 for (int i = 0; i < 100; i++) { 116 performSet(); 117 } 118 } 119 catch (Throwable e) { 120 test.ex = e; 121 } 122 finally { 123 synchronized (test) { 124 test.set.remove(this); 125 test.notifyAll(); 126 } 127 } 128 } 129 } 130 131 132 private static class TestBean { 133 134 private Properties properties; 135 136 public Properties getProperties() { 137 return properties; 138 } 139 140 public void setProperties(Properties properties) { 141 this.properties = properties; 142 } 143 } 144 145 } 146 | Popular Tags |