1

I want to write a code block where I want my thread to sleep for say 10 minutes. I can do it via Thread.sleep().

But, I want to release the acquired lock. So other thread can use it. I may use object.wait() in this situation. But I can't as other thread that acquire lock does notify() after processing. So my thread is woke up again may be prior to 10 minutes.

What I need is exact sleep of 10 minutes and Also, I do not want to hold lock. So that other threads may use it.

Please assist. Thanks

dinesh028
  • 2,137
  • 5
  • 30
  • 47
  • 2
    release the lock / sleep / reacquire the lock? – assylias Mar 11 '15 at 11:05
  • reacquire lock only after sleep of anticipated time (say 10 min). If any other thread calls notify then also I do not want sleeping thread to wake prior 10min expiration. – dinesh028 Mar 11 '15 at 11:07
  • Basically I wan't to wait and release the lock. But wake up ony after expiration of sleep time no matters if other threads call notify. – dinesh028 Mar 11 '15 at 11:09
  • 1
    Why don't you simply release the lock before sleeping like I suggested? – assylias Mar 11 '15 at 11:10
  • 1
    Sleep outside of the synchronized block. Then open a new synchronized block (re-acquire lock). – Brett Okken Mar 11 '15 at 11:11
  • 1
    Use `notify` --> `Thread#Sleep()` --> Sleep Completed --> `Reaquire lock` – Neeraj Jain Mar 11 '15 at 11:27
  • and Read this [Difference between wait() and sleep()](http://stackoverflow.com/a/1036763/3143670) – Neeraj Jain Mar 11 '15 at 11:31
  • @assylias - Thanks got your point. Just one thing which is better, I mean another way can be to call while(true){ if(!condition) {obj.wait()}}.. or simply like you put it sync(obj){} sleep() sync(obj){} – dinesh028 Mar 11 '15 at 11:32

1 Answers1

2

Use a ScheduledExecutorService.

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

scheduler.schedule(runnableTask, 10, TimeUnit.MINUTES);

where runnableTask is an instance of a class that implements Runnable and has the code you want to run in its run() method.

If you need that your code returns a value, use a Callable instead of a Runnable.

You might want to use a synchronized block with a lock in your code or any other concurrency construction to avoid that more than one thread runs your code concurrently.

fps
  • 33,623
  • 8
  • 55
  • 110