Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wait() and notify()

 
Faraah Dabhoiwala
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
which object should be marked synchronized when we want a thread to wait??

how does a thread know which object amongst those which are waiting to notify??

 
Henry Wong
author
Marshal
Pie
Posts: 21194
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For first question, see my response here...

http://www.coderanch.com/t/233995/Threads-Synchronization/java/synchronization


For second question, most modern JVMs pass the threading to the underlying OS libraries. So it is the OS libraries that choose the waiting thread. As for the Java Specification, it doesn't require any order or preference.

Henry
 
Faraah Dabhoiwala
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
didnt get what you wrote there
 
Henry Wong
author
Marshal
Pie
Posts: 21194
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shadab Wadiwala wrote:didnt get what you wrote there


It looks like you reworded you question, after I answered it. I read the previous question as why synchronization was needed.

Henry
 
Henry Wong
author
Marshal
Pie
Posts: 21194
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
which object should be marked synchronized when we want a thread to wait??


The object that will be used to wait, should be the object that needs to be synchronized.

Henry
 
Balraj Momi
Ranch Hand
Posts: 45
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all ,you should know that objects don't wait for threads, Its opposite. Threads actually wait for an notification so that they can continue their operation. One thread can own multiple locks but one object lock can only be owned by one thread.

Let me put it this way, following is an example where a machine is waiting for a for a job to work on. Here job is a object and as soon as a new job is build, machine will get notification to continue to work on that job.



Though all of you may agree that, this code is not foolproof, for example notify can happen even before wait starts. This is just to help Shadab understand how threads owns lock on an object and gets notified to reclaim their property .

Regards
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic