Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sleep() method concept

 
Faisal syed
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,
Here is the piece of code

synchronized(LOCK) {
Thread.sleep(1000); // LOCK is held
}

.

We know that the sleep method() does not release the lock. Hence, no other object can access the above piece of code even
if this thread is asleep. So, I am confused why is sleep used in this context! sleep() is used to give other threads a chance to get back into
runnable( or may be running). Aint't it?
Please help.

Thanks
Faisal
 
Nam Ha Minh
Ranch Hand
Posts: 504
Eclipse IDE Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, the sleep() method does not release the lock or give chance to other threads, just sleeping. You may be confused with Object.wait(). Use wait() if you want to do something like sleep() but does release the lock.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, I am confused why is sleep used in this context! sleep() is used to give other threads a chance to get back into
runnable( or may be running). Aint't it?


First, there really is no context provided in your code snipped, so it is impossible to say why it was used where you question it.

But sleep() is used to stop this thread from using CPU cycles. This might be used to let other threads a chance to do work and advance in their own sequences, or it might be used simply because this thread has nothing to do for a little while. Why would you specifically put a sleep inside a synchronized block without anything else? I think I need more context to see why - I could imagine there might be a reason to do it for testing an proof-of-concept purposes (create a situation where a thread holds on to a lock for a period of time and simulate doing work). Or if there is a reason to prevent the lock from being taken by another thread for a fixed period of time for some reason. Or maybe there are multiple threads that could reach this code and you want to make sure that they sleep() in sequence rather than in parallel.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic