1 10 package org.picocontainer.defaults; 11 12 import junit.framework.TestCase; 13 14 17 public class CyclicDependencyGuardTestCase 18 extends TestCase { 19 private Runnable [] runner = new Runnable [3]; 20 21 class ThreadLocalRunner implements Runnable { 22 public CyclicDependencyException exception; 23 private final Blocker blocker; 24 private final CyclicDependencyGuard guard; 25 26 public ThreadLocalRunner() { 27 this.blocker = new Blocker(); 28 this.guard = new ThreadLocalCyclicDependencyGuard() { 29 public Object run() { 30 try { 31 blocker.block(); 32 } catch (InterruptedException e) { 33 } 34 return null; 35 } 36 }; 37 } 38 39 public void run() { 40 try { 41 guard.observe(ThreadLocalRunner.class); 42 } catch (CyclicDependencyException e) { 43 exception = e; 44 } 45 } 46 } 47 48 public class Blocker { 49 public void block() throws InterruptedException { 50 final Thread thread = Thread.currentThread(); 51 synchronized (thread) { 52 thread.wait(); 53 } 54 } 55 } 56 57 private void initTest(final Runnable [] runner) throws InterruptedException { 58 59 Thread racer[] = new Thread [runner.length]; 60 for(int i = 0; i < racer.length; ++i) { 61 racer[i] = new Thread (runner[i]); 62 } 63 64 for(int i = 0; i < racer.length; ++i) { 65 racer[i].start(); 66 Thread.sleep(200); 67 } 68 69 for(int i = 0; i < racer.length; ++i) { 70 synchronized (racer[i]) { 71 racer[i].notify(); 72 } 73 } 74 75 for(int i = 0; i < racer.length; ++i) { 76 racer[i].join(); 77 } 78 } 79 80 public void testCyclicDependencyWithThreadSafeGuard() throws InterruptedException { 81 for(int i = 0; i < runner.length; ++i) { 82 runner[i] = new ThreadLocalRunner(); 83 } 84 85 initTest(runner); 86 87 for(int i = 0; i < runner.length; ++i) { 88 assertNull(((ThreadLocalRunner)runner[i]).exception); 89 } 90 } 91 } 92 | Popular Tags |