aspose file tools
The moose likes Java in General and the fly likes Why wait() method need to define in synchronized context? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Why wait() method need to define in synchronized context?" Watch "Why wait() method need to define in synchronized context?" New topic
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
    
    1

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
    
    1

You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why wait() method need to define in synchronized context?
 
Similar Threads
java.lang. IllegalMonitorStateException: current thread not owner
Thread Doubt
Wait() a confusion
wait() in synchronized code ??
wait()