1

Suppose I have synchronized two parts of code within a method. So block1 and block2 each have keyword 'synchronized' around them, and both use 'this', meaning both blocks are guarded by same object lock.

Now if block1 is being executed by a thread, does it mean no other thread can execute block2?

Mandroid
  • 6,200
  • 12
  • 64
  • 134
  • 1
    Yes. [filler text] – akuzminykh Jul 05 '20 at 08:45
  • One and only one synchronized method can run at a given time. A call to the other synchronized method will have to wait until the first method is done. – Amit kumar Jul 05 '20 at 08:50
  • 1
    @Amitkumar That's not correct, and it doesn't answer the question either. Who can execute a `synchronized` block or method depends on what object is being synchronized on. – user207421 Jul 05 '20 at 10:10
  • Last I read, When there are multiple synchronized methods(both static and instance) in a class, `Java` allows only one such method to run at a time. – Amit kumar Jul 05 '20 at 10:32
  • 1
    @Amitkumar That is not how it works. A non-static synchronized method, synchronizes on an **instance**, so multiple non-static synchronized methods cannot run concurrently on the **same object**, but can run on **different** objects. A non-static synchronized method is equivalent to `synchronize(this) {...}` over the entire method body. Static synchronized methods synchronize on the class, so multiple static synchronized methods on the **same class** cannot run concurrently. Static synchronized methods don't block non-static synchronized methods and vice versa. – Mark Rotteveel Jul 05 '20 at 11:08
  • Thanks for clarification! Good learning exercise for me. – Amit kumar Jul 05 '20 at 11:17

1 Answers1

2

Synchronized on the method declaration is the same as:

public void method() {
    synchronized (this) {
       // method code
    }
}

Having said that, as you can see in the oracle docs you can see an example with some synchronized methods and it says:

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

So, yes, no other thread can execute block2 in that case.

jeprubio
  • 17,312
  • 5
  • 45
  • 56