0

If a class has these two methods:

public static synchronized void m1() {}

public synchronized void m2() {}

Can two threads execute these two methods at the same time?

Aleximimus
  • 17
  • 4

1 Answers1

1

Yes, two threads can execute these two methods at the same time. The static method synchronizes on the class, the other method on the object itself.

In other words, a static method is an equivalent of this code block:

synchronized(MyClass.class) {
...
}

where MyClass is the class where the static method is defined. Note that it's not the same as this.getClass() in non-static methods as getClass() returns the most derived class.

Henry
  • 42,982
  • 7
  • 68
  • 84
  • 1
    @Makoto that answer is about two instance methods. Here you have an instance method and a static method, so yes, this answer is correct, as the static method has no instance to acquire the lock on. – BackSlash May 30 '18 at 17:18
  • 1
    @Makoto Turns out, the duplicate is not a duplicate - the situation is different here. One method is static, the other isnt. – Henry May 30 '18 at 17:19
  • @Henry: Fair enough. I'll change the dupe target. – Makoto May 30 '18 at 17:20
  • ...So instead of looking for a *better* dupe, it's fine to reopen the question. Okay. I'll retreat for now, then. – Makoto May 30 '18 at 17:24
  • @Makoto I found a better dupe. – Henry May 30 '18 at 17:32
  • So if i understood correctly, then if both methods were static they couldn't be executed at the same time. The same would happen if both of them didn't have the static modifier? – Aleximimus May 30 '18 at 17:47
  • @user9871742 yes, this is correct. – Henry May 30 '18 at 17:51