• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why wait() method need to define in synchronized context?  RSS feed

 
Mohammad Sufiyan Al Yousufi
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Saloon Keeper
Posts: 7933
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Stephan. Very nice explaination. I appreciate your effort.
 
Stephan van Hulst
Saloon Keeper
Posts: 7933
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!