Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling Thread.sleep() from synchronized context in Java

I have read that Thread.sleep() will pause the currently running thread for the time specified after which it goes back to runnable state waiting for it's turn to run.

Also, if called from synchronized context, sleep() doesn't release the lock it holds. So I was wondering when it will release the lock. If the thread, put on sleep, never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methods/block.

I am not sure if I am asking valid question. But please help me out.

like image 884
Anand Avatar asked May 19 '12 09:05

Anand


People also ask

Is thread sleep synchronized?

If the thread, put on sleep, never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methods/block. Quite simply, other threads will not be able to enter code that's synchronized on the same object that the sleeping thread.

What happens if sleep () and wait () executes in synchronized block?

The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.

What happens when thread's sleep () method is called?

Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

What is difference between calling wait () and sleep () method in Java multithreading?

Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization. Wait() should be called only from Synchronized context.


2 Answers

So I was wondering when it will release the lock.

It will release the lock upon exit from the synchronized block, and not earlier.

If the thread, put on sleep, never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methods/block.

Quite simply, other threads will not be able to enter code that's synchronized on the same object that the sleeping thread.

To summarize, calling Thread.sleep() from a synchronized block is likely not a good idea.

like image 62
NPE Avatar answered Sep 22 '22 11:09

NPE


If you use Object.wait instead of Thread.sleep, the lock from the synchronized block will be released.

like image 31
nosid Avatar answered Sep 21 '22 11:09

nosid