Does a thread release the lock that he obtained when going to sleep state in a synchronized method?
Asked
Active
Viewed 660 times
1
-
4Quick Google search shows [this question](http://stackoverflow.com/questions/10663920/calling-thread-sleep-from-synchronized-context-in-java), which seems to imply that it does not. Could be a dupe; borderline to me. The first half of the accepted answer applies here. – Nic Feb 15 '15 at 03:21
-
1Maybe it could be sated in the question (and not only in the tags) that it is about java threads ? – PatJ Feb 15 '15 at 03:25
2 Answers
1
Thread.sleep API says "The thread does not lose ownership of any monitors" which means that thread does not release locks while sleeping

Evgeniy Dorofeev
- 133,369
- 30
- 199
- 275
0
As the answer in the older question already state, it will not release the lock. Would be really bad if it did.

Community
- 1
- 1

Janick Bernet
- 20,544
- 2
- 29
- 55
-
It actually does release it if you do `this.wait();`, but I think that puts the thread in the waiting state, not sleep. – David Ehrmann Feb 15 '15 at 04:27
-
Yes, the question was about sleep though. That is exactly the difference between the two. Sleep just yields thread execution for a specific amount of time, it is completely independent from any locking. – Janick Bernet Feb 15 '15 at 04:29
-
I've actually seen code where `this.wait(...);` was used instead of `Thread.sleep(...)` because someone didn't read the documentation. It's also a bit of a surprise that you can call a `synchronized` method nearly concurrently with some monitor trickery. `synchronized` guarantees only one thread is *running* that method on a given object, not that only one thread is *in* it. – David Ehrmann Feb 15 '15 at 04:34
-
I'm not entirely sure what you mean by 'running' vs 'in'? Definitely if someone would use `wait` instead of `sleep` this would generally throw, as `wait` will not work if the current thread doesn't hold the monitor. – Janick Bernet Feb 15 '15 at 04:36
-
It did, so they `synchronized` *just* so they could sleep. By "running," I mean actively executing. By "in," I mean having a thread with a call stack that includes that method, but the thread isn't currently being executed. – David Ehrmann Feb 15 '15 at 04:41
-
Thanks a lot for your answers mates. Appreciate your time and effort. :) – t4thilina Feb 15 '15 at 04:50