Only 48 hours left in the trailboss' kickstarter!

New rewards and stretch goals. CLICK HERE!



  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to set timer for wait() call  RSS feed

 
Vinney Shanmugam
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is my code which waits for notification from some other thread. In case, if i dont want it to be indefinitely waiting for the notification, how can i give a timer value to keep waiting till that time and once that time is reached, come out of wait().

try {
wait();
} catch (InterruptedException e) {
}

I have tried wait(time) API. Can it be done without this using Timer class?
 
Campbell Ritchie
Sheriff
Posts: 53720
127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I always thought it was obj.wait(1000); for 1 second. Remember the timing depends on the system clock, and is not precise.

Sounds like a thread which would get better attention on the threads forum, so I shall move you.
 
Pawan Arora
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
whenever you declare wait method in any method of an object, you have to declare it synchronized, otherwise an unchecked exception will be thrown.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vinod:I have tried wait(time) API. Can it be done without this using Timer class?


Yeah it can be done via the Timer class but i would not suggest it.
The reason being that you will start a new thread(if Timer is not already used) to keep a watch on the running thread. More so, if the only task of the timer is to notify when the time lapses.
The best way is to use the timed wait method.

Pawan: whenever you declare wait method in any method of an object, you have to declare it synchronized, otherwise an unchecked exception will be thrown.

The unchecked exception is IllegalMonitorStateException
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!