-2

If a thread is executing a synchronized method, will it release the lock of that object before fully completing the execution of that method ? If yes, in what kind of case ?

If one thread(A) is executing synchronized method and at same time other thread(B) tries to access same synchronized method (or any other synchronized method in that object) it will go to BLOCKED state, but if the other thread(B) tries to access non-synchronized method will it get the execution before the first thread(A) completes the execution of the synchronized method ? Or it will get the execution only after the first thread(A) completes the execution of synchronized method ?

Half Blood Prince
  • 951
  • 2
  • 13
  • 25

1 Answers1

1

A synchronized method is just a shortcut way of writing a synchronized block (see https://stackoverflow.com/a/26676499/801894). So, no matter whether you are talking about a synchronized instance method, or a synchronized static method or a synchronized block, you really are talking about the same thing in all three cases.

Java will never allow more than one thread to be synchronized on the same object at the same time. The only tricky part of understanding that rule is to know that if a thread calls foo.wait() from inside a synchronized(foo){...} block, then the thread will not be synchronized for some interval of time while it is inside the foo.wait() call. But, it is guaranteed that the thread will synchronize on foo again before the foo.wait() call returns.

The only other way a thread can give up its synchronization of foo is to leave the synchronized(foo) {...} block altogether.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57