2

What happens if a thread executing a synchronized method suspends? Will other Threads get the lock and proceed with another synchronized method in the same class..?

Suppose the code is like:

class Test{
   public synchronized void methodA(){
      //methodA
   }
   public synchronized void methodB(){
      //methodB
   }
}

If ThreadA execute methodA(). And while executing the method if it get suspended implicitly by the OS. Will another Thread, say ThreadB can get the lock and execute methodB()? or is it possible only after the ThreadA completes its work with methodA()?

Hakan Dilek
  • 2,178
  • 2
  • 23
  • 35
Jithin M V
  • 175
  • 1
  • 1
  • 10
  • [What will happen if thread throws a Exception inside synchronised block](https://stackoverflow.com/questions/30660236/what-will-happen-if-thread-throws-a-exception-inside-synchronised-block), [What happens to the lock when thread crashes inside a Synchronized block?](https://stackoverflow.com/questions/12521776/what-happens-to-the-lock-when-thread-crashes-inside-a-synchronized-block) – akuzminykh Jul 20 '20 at 09:30

2 Answers2

3

No, it won't force the thread to relinquish the lock since it would break the whole idea of synchronization. It is possible to exit the monitor via wait method call on the object (declared in the Object class) to give other threads a chance to enter it .

Andrew Vershinin
  • 1,958
  • 11
  • 16
0

Following text from book Java - The Complete Reference should help :

This was done because suspend( ) can sometimes cause serious system failures. Assume that a thread has obtained locks on critical data structures. If that thread is suspended at that point, those locks are not relinquished. Other threads that may be waiting for those resources can be deadlocked.

Ankit Chauhan
  • 646
  • 6
  • 20