| Author |
Why wait() method need to define in synchronized context?
|
Mohammad Sufiyan Al Yousufi
Greenhorn
Joined: Aug 30, 2010
Posts: 11
|
|
Hi
I have one simple question, why wati() has to be called from Synchronized method or block? The thread will execute wait() method only when it has lock on the object and when executes, it give out the lock and go to block state. This questions seems to be simple but I really confused regarding this?
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3065
|
|
Welcome to JavaRanch!
Think about it, why would you ever want to call wait()? Only because you are about to do some work with data that isn't ready yet, some way or another, and which needs to be prepared by another thread. So if two threads have access to the same data, you want to synchronize the data between them. There is no case where it makes sense to call wait() in a setting that isn't synchronized somehow.
Also, I would imagine forcing this restriction makes it easier to implement the function, because the Java designers can use the default object monitors to make wait() block.
|
 |
Mohammad Sufiyan Al Yousufi
Greenhorn
Joined: Aug 30, 2010
Posts: 11
|
|
|
Thank you Stephan. Very nice explaination. I appreciate your effort.
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3065
|
|
You're welcome
|
 |
 |
|
|
subject: Why wait() method need to define in synchronized context?
|
|
|