Hi All
I have a task, I need to execute this task only if I meet a condition.
I wrote the function
didIMeetCondition()
which returns boolean.
I have a threshold value of time to which I can wait till my condition
returns true.
After the threshold I need to throw exception if y condition return
false.
How do I write code to do this. Just psuedo code is sufficient.
Any ideas, please let me know.
Thanks
Bib
Gordon Beaton - 25 Apr 2007 07:23 GMT
> I have a threshold value of time to which I can wait till my
> condition returns true. After the threshold I need to throw
> exception if y condition return false.
>
> How do I write code to do this. Just psuedo code is sufficient.
long now = System.currentTimeMillis();
long limit = now + timeoutMillis;
synchronized (obj) {
while ((!obj.didIMeetCondition()) &&
((now=System.currentTimeMillis()) < limit)) {
obj.wait(limit - now);
}
}
if (now >= limit) {
throw new MyException("condition not met");
}
The code that sets the condition should be synchronized on the same
"obj", and must call obj.notify() after making the change.
/gordon
--
Jeffrey Schwab - 25 Apr 2007 13:07 GMT
> Hi All
>
[quoted text clipped - 9 lines]
> After the threshold I need to throw exception if y condition return
> false.
You might want Future.get(long timeout, TimeUnit unit), or one of the
other classes that throw TimeoutException.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/class-use/TimeoutEx
ception.html