java - Can anyone explain thread monitors and wait? -
someone @ work asked reasoning behind having wrap wait inside synchronized.
honestly can't see reasoning. understand javadocs say--that thread needs owner of object's monitor, why? problems prevent? (and if it's necessary, why can't wait method monitor itself?)
i'm looking in-depth why or maybe reference article. couldn't find 1 in quick google.
oh, also, how thread.sleep compare?
edit: great set of answers--i wish select more 1 because helped me understand going on.
if object not own object monitor when calls object.wait(), not able access object setup notify listener until the monitor released. instead, treated thread attempting access method on synchronized object.
or put way, there no difference between:
public void dostuffonthisobject()
and following method:
public void wait()
both methods blocked until object monitor released. feature in java prevent state of object being updated more 1 thread. has unintended consequences on wait() method.
presumably, wait() method not synchronized because create situations thread has multiple locks on object. (see java language specifications/locking more info on this.) multiple locks problem because wait() method undo 1 lock. if method synchronized, guarantee method's lock undone while still leaving potential outer lock undone. create deadlock condition in code.
to answer question on thread.sleep(), thread.sleep() not guarantee whatever condition waiting on has been met. using object.wait() , object.notify() allows programmer manually implement blocking. threads unblock once notify sent condition has been met. e.g. read disk has finished , data can processed thread. thread.sleep() require programmer poll if condition has been met, fall sleep if has not.
Comments
Post a Comment