1 3 package org.jgroups.tests; 4 5 6 import junit.framework.TestCase; 7 import org.jgroups.TimeoutException; 8 import org.jgroups.util.Promise; 9 import org.jgroups.util.Util; 10 11 12 16 public class PromiseTest extends TestCase { 17 Promise p; 18 19 public PromiseTest(String name) { 20 super(name); 21 } 22 23 public void setUp() throws Exception { 24 super.setUp(); 25 p=new Promise(); 26 } 27 28 29 public void tearDown() throws Exception { 30 p.reset(); 31 super.tearDown(); 32 } 33 34 35 public void testGetResultNoTimeout() { 36 Object result; 37 new ResultSetter(p, 500).start(); 38 result=p.getResult(0); 39 assertEquals(result, Boolean.TRUE); 40 } 41 42 public void testGetResultNoTimeout_ResultAlreadySet() { 43 Object result; 44 new ResultSetter(p, 1).start(); 45 Util.sleep(100); 46 result=p.getResult(0); 47 assertEquals(result, Boolean.TRUE); 48 } 49 50 public void testGetResultWithTimeout() { 51 try { 52 p.getResultWithTimeout(500); 53 fail("this should throw a TimeoutException"); 54 } 55 catch(TimeoutException e) { 56 assertTrue(e != null); 57 } 58 } 59 60 61 public void testGetResultWithTimeoutNoException() { 62 Object ret=p.getResult(500); 63 assertNull(ret); 64 } 65 66 public void testGetResultWithTimeoutAndInterrupt() { 67 new Interrupter(Thread.currentThread(), 100).start(); 68 Object result=p.getResult(500); 69 assertNull(result); 70 } 71 72 73 public void testGetResultWithTimeoutAndResultSetter() { 74 Thread t=new Thread () { 75 public void run() { 76 Util.sleep(500); 77 System.out.println("-- setting promise to \"Bela\""); 78 p.setResult("Bela"); 79 } 80 }; 81 t.start(); 82 long start=System.currentTimeMillis(), stop; 83 Object result=p.getResult(100000); 84 stop=System.currentTimeMillis(); 85 System.out.println("-- waited for " + (stop-start) + "ms, result is " + result); 86 assertNotNull(result); 87 assertEquals("Bela", result); 88 assertFalse("promise was reset after getResult()", p.hasResult()); 89 } 90 91 92 93 94 static class ResultSetter extends Thread { 95 long wait_time=2000; 96 Promise target=null; 97 98 ResultSetter(Promise target, long wait_time) { 99 this.target=target; 100 this.wait_time=wait_time; 101 } 102 103 public void run() { 104 Util.sleep(wait_time); 105 target.setResult(Boolean.TRUE); 106 } 107 } 108 109 110 static class Interrupter extends Thread { 111 long wait_time=2000; 112 Thread target=null; 113 114 Interrupter(Thread target, long wait_time) { 115 this.target=target; 116 this.wait_time=wait_time; 117 } 118 119 public void run() { 120 Util.sleep(wait_time); 121 target.interrupt(); 122 } 123 } 124 125 126 public static void main(String [] args) { 127 String [] testCaseName={PromiseTest.class.getName()}; 128 junit.textui.TestRunner.main(testCaseName); 129 } 130 131 } 132 | Popular Tags |