1 3 package org.jgroups.util; 4 5 import org.jgroups.TimeoutException; 6 7 8 14 public class Promise { 15 Object result=null; 16 boolean hasResult=false; 17 18 19 25 public Object getResultWithTimeout(long timeout) throws TimeoutException { 26 synchronized(this) { 27 try { 28 return _getResultWithTimeout(timeout); 29 } 30 finally { 31 notifyAll(); 32 } 33 } 34 } 35 36 37 44 private Object _getResultWithTimeout(long timeout) throws TimeoutException { 45 Object ret=null; 46 long time_to_wait=timeout, start; 47 boolean timeout_occurred=false; 48 49 start=System.currentTimeMillis(); 50 while(hasResult == false) { 51 if(timeout <= 0) { 52 doWait(); 53 } 54 else { 55 if(time_to_wait <= 0) { 56 timeout_occurred=true; 57 break; } 59 else { 60 doWait(time_to_wait); 61 time_to_wait=timeout - (System.currentTimeMillis() - start); 62 } 63 } 64 } 65 66 ret=result; 67 result=null; 68 hasResult=false; 69 if(timeout_occurred) 70 throw new TimeoutException(); 71 else 72 return ret; 73 } 74 75 public Object getResult() { 76 try { 77 return getResultWithTimeout(0); 78 } 79 catch(TimeoutException e) { 80 return null; 81 } 82 } 83 84 89 public Object getResult(long timeout) { 90 try { 91 return getResultWithTimeout(timeout); 92 } 93 catch(TimeoutException e) { 94 return null; 95 } 96 } 97 98 99 void doWait() { 100 try {wait();} catch(InterruptedException e) {} 101 } 102 103 void doWait(long timeout) { 104 try {wait(timeout);} catch(InterruptedException e) {} 105 } 106 107 108 109 110 113 public boolean hasResult() { 114 synchronized(this) { 115 return hasResult; 116 } 117 } 118 119 123 public void setResult(Object obj) { 124 synchronized(this) { 125 result=obj; 126 hasResult=true; 127 notifyAll(); 128 } 129 } 130 131 132 135 public void reset() { 136 synchronized(this) { 137 result=null; 138 hasResult=false; 139 notifyAll(); 140 } 141 } 142 143 144 public String toString() { 145 return "hasResult=" + hasResult + ",result=" + result; 146 } 147 148 149 } | Popular Tags |