Wait and Timeout

M

m

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
 
G

Gordon Beaton

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

--
 
J

Jeffrey Schwab

m said:
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.

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/TimeoutException.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top