1 package edu.rice.cs.util; 2 import junit.framework.*; 3 4 7 public class CompletionMonitorTest extends TestCase { 8 9 private boolean _shouldInterrupt; 10 11 public void testDegenerateSignal() { 12 13 CompletionMonitor as = new CompletionMonitor(true); 14 assertTrue("Flag should start out as true", as.isFlag()); 15 17 ThreadInterrupter interrupter = new ThreadInterrupter(); 18 interrupter.start(); 19 20 assertTrue("WaitOne hung, and was interrupted by the failsafe.", as.waitOne()); 21 interrupter.targetCompleted(); 22 } 23 24 public void testRealSignal() { 25 final CompletionMonitor as = new CompletionMonitor(false); 26 Thread worker = new Thread () { 27 public void run() { 28 try { 29 Thread.sleep(50); 30 as.set(); 31 } catch (InterruptedException e) { 32 } 33 } 34 }; 35 worker.start(); 36 assertTrue("WaitOne hung", as.waitOne()); 37 assertTrue(as.waitOne()); 38 as.reset(); 39 assertFalse("Reset failed to do its job", as.isFlag()); 40 } 41 42 private static class ThreadInterrupter { 43 44 private Object _lock = new Object (); 45 46 private int _timeout; 47 private boolean _targetComplete; 48 49 private Thread _target; 50 51 private Thread _interrupter = new Thread () { 52 public void run() { 53 synchronized(_lock) { 54 try { 55 58 if (!_targetComplete) _lock.wait(_timeout); 59 } 60 catch(InterruptedException e) { 61 } 63 finally { 64 if(!_targetComplete) _target.interrupt(); 67 } 68 } 69 } 70 }; 71 72 public ThreadInterrupter() { 73 this(Thread.currentThread(), 50); 74 } 75 76 public ThreadInterrupter(int timeout) { 77 this(Thread.currentThread(), timeout); 78 } 79 80 public ThreadInterrupter(Thread target, int timeout) { 81 _target = target; 82 _timeout = timeout; 83 _targetComplete = false; 84 } 85 86 public void start() { 87 _interrupter.start(); 88 } 89 90 public void targetCompleted() { 91 synchronized(_lock) { 92 _targetComplete = true; 93 _lock.notify(); 94 } 95 } 96 } 97 } 98 | Popular Tags |