1 46 package net.jforum.util.concurrent.executor; 47 48 import net.jforum.util.concurrent.Result; 49 import net.jforum.util.concurrent.Task; 50 51 54 class SimpleResult implements Result 55 { 56 private final Task task; 57 private Exception exception; 58 private Object result; 59 private boolean ready = false; 60 private final Object lock = new Object (); 61 62 SimpleResult(Task task) 63 { 64 this.task = task; 65 } 66 67 public boolean hasThrown() throws IllegalStateException 68 { 69 synchronized(lock) { 70 if(!ready) { 71 throw new IllegalStateException ("task has not completed"); 72 } 73 74 return exception != null; 75 } 76 } 77 78 public Object getResult() throws IllegalStateException 79 { 80 synchronized(lock) { 81 if(!ready) { 82 throw new IllegalStateException ("task has not completed"); 83 } 84 85 if(exception != null) { 86 throw new IllegalStateException ("task has thrown an exception"); 87 } 88 89 return result; 90 } 91 } 92 93 public Exception getException() throws IllegalStateException 94 { 95 synchronized(lock) { 96 if(!ready) { 97 throw new IllegalStateException ("task has not completed"); 98 } 99 100 if(exception == null) { 101 throw new IllegalStateException ("task has not thrown an exception"); 102 } 103 104 return exception; 105 } 106 } 107 108 public synchronized void waitResult() throws InterruptedException 109 { 110 if(Thread.interrupted()) { 111 throw new InterruptedException (); 112 } 113 114 synchronized(lock) { 115 if(ready) { 116 return; 117 } 118 119 while(!ready) { 120 lock.wait(); 121 } 122 } 123 } 124 125 public synchronized boolean poolResult(long timeout) throws InterruptedException 126 { 127 if(Thread.interrupted()) { 128 throw new InterruptedException (); 129 } 130 131 synchronized(lock) { 132 if(ready) { 133 return true; 134 } 135 136 if(timeout <= 0) { 137 return false; 138 } 139 140 long remaining = timeout; 141 long start = System.currentTimeMillis(); 142 143 for(;;) { 144 lock.wait(remaining); 145 if(ready) { 146 return true; 147 } 148 149 remaining = timeout - (System.currentTimeMillis() - start); 150 if(remaining <= 0) { 151 return false; 152 } 153 } 154 } 155 } 156 157 void setException(Exception exception) 158 { 159 synchronized(lock) { 160 if(ready) { 161 throw new IllegalStateException ("task allready completed"); 162 } 163 164 this.exception = exception; 165 ready = true; 166 lock.notifyAll(); 167 } 168 } 169 170 void setResult(Object result) 171 { 172 synchronized(lock) { 173 if(ready) { 174 throw new IllegalStateException ("task allready completed"); 175 } 176 177 this.ready = true; 178 this.result = result; 179 lock.notifyAll(); 180 } 181 } 182 183 Task getTask() 184 { 185 return task; 186 } 187 188 } | Popular Tags |