Wait and Timeout

Discussion in 'Java' started by m, Apr 25, 2007.

  1. m

    m Guest

    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
    m, Apr 25, 2007
    #1
    1. Advertising

  2. On 24 Apr 2007 16:07:13 -0700, m wrote:
    > 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

    --
    Gordon Beaton, Apr 25, 2007
    #2
    1. Advertising

  3. m wrote:
    > 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
    Jeffrey Schwab, Apr 25, 2007
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. LL
    Replies:
    7
    Views:
    15,987
    Nico Schuyt
    Aug 31, 2004
  2. Huey

    How to make "fork/wait" to WAIT longer?

    Huey, Mar 1, 2004, in forum: C Programming
    Replies:
    1
    Views:
    1,958
    -berlin.de
    Mar 1, 2004
  3. Tiwkiz
    Replies:
    0
    Views:
    616
    Tiwkiz
    Jan 27, 2007
  4. Mark Probert

    Timeout::timeout and Socket timeout

    Mark Probert, Oct 6, 2004, in forum: Ruby
    Replies:
    1
    Views:
    1,279
    Brian Candler
    Oct 6, 2004
  5. Sharat Mohan
    Replies:
    0
    Views:
    91
    Sharat Mohan
    Feb 11, 2009
Loading...

Share This Page