Mercenary
Mercenary

Reputation: 2166

Call to Synchronization/wait?

Could anyone just help me understand this?

If we have a class:

public class Sample{
 public synchronized method1(){ //Line1
  ....
  wait(); //Line2
  ....
 }
}

Now, when 3 new threads try to call the method 'method1' on the same object

Sample s = new Sample();
Thread t1 = new Thread(); // t2 and t3

and inside run method of each of these threads, we call s.method1(). So, how does it work here? When t1 accesses method1, it goes in the method and calls wait. What about the rest of the threads when it tries to access method1?

Do they get blocked on the method1 since synchronization allows only one thread to access the object instance at a time? Or do they go to wait state?

Upvotes: 2

Views: 190

Answers (2)

Braj
Braj

Reputation: 46871

Lock is obtained on object. In this case since there is only one object s on which all the threads are trying to call same method method1 hence only one thread can enter in the method.

What about the rest of the threads when it tries to access method1?

You are calling wait on this object, hence lock is released and other threads will get chance but in last all 3 threads will reach in block state because there is no one to notify it.

Nothing will be executed after wait() statement for all 3 threads.

Do they get blocked on the method1 since synchronization allows only one thread to access the object instance at a time?

wait() release the lock hence this will not block other thread to access the same method but if you are not calling notify then in last all threads will enter in blocked state.

Try to visualize it

enter image description here

enter image description here

Upvotes: 5

Chris K
Chris K

Reputation: 11925

The key part is that wait() will release the monitor that the calling thread is synchronizing against, thus allowing other threads in to the same synchronized block.

However, be warned that it will not release any other monitors that are also held by that thread, which is can lead to deadlock. This is why nesting synchronized calls can be dangerous.

This monitor behaviour is documented here

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

Upvotes: 3

Related Questions