1 10 package org.picocontainer.gems.adapters; 11 12 import junit.framework.Assert; 13 import junit.framework.TestCase; 14 15 import org.picocontainer.defaults.ObjectReference; 16 17 import java.util.ArrayList ; 18 import java.util.Collections ; 19 import java.util.List ; 20 21 22 27 public class ThreadLocalReferenceTest extends TestCase { 28 29 private List m_exceptionList; 30 31 34 protected void setUp() throws Exception { 35 super.setUp(); 36 m_exceptionList = Collections.synchronizedList(new ArrayList ()); 37 } 38 39 final class RunIt implements Runnable { 40 41 private ObjectReference m_reference; 42 43 48 public RunIt(ObjectReference reference) { 49 super(); 50 m_reference = reference; 51 } 52 53 56 public void run() { 57 try { 58 final Thread thread = Thread.currentThread(); 59 m_reference.set(thread.getName()); 60 synchronized (thread) { 61 thread.wait(); 62 } 63 Assert.assertEquals(thread.getName(), m_reference.get()); 64 } catch (InterruptedException e) { 65 m_exceptionList.add(e); 66 } 67 } 68 } 69 70 75 public final void testThreadLocalReference() throws InterruptedException { 76 final ThreadLocalReference reference = new ThreadLocalReference(); 77 final Thread [] threads = new Thread []{ 78 new Thread (new RunIt(reference), "junit-TLR-1"), new Thread (new RunIt(reference), "junit-TLR-2"), 79 new Thread (new RunIt(reference), "junit-TLR-3")}; 80 reference.set("Hello"); 81 for (int i = 0; i < threads.length; i++) { 82 threads[i].start(); 83 } 84 Thread.sleep(50); 85 assertEquals("Hello", reference.get()); 86 for (int i = 0; i < threads.length; i++) { 87 synchronized (threads[i]) { 88 threads[i].notify(); 89 } 90 } 91 Thread.sleep(50); 92 assertEquals("Unexpected Exceptions: " + m_exceptionList, 0, m_exceptionList.size()); 93 } 94 } 95 | Popular Tags |