1

My questions is about Java. Can several threads access a static method of a static class at the same time or can only one thread at a time executing the method?

If I use synchronized in the method header, only one thread can execute it at a time?

machinery
  • 5,972
  • 12
  • 67
  • 118

1 Answers1

3

Can several threads access a static method of a static class at the same time or can only one thread at a time executing the method?

Yes, they can. Unless the method is synchronized, there is no constraint on the number of threads that can access that method.

If I use synchronized in the method header, only one thread can execute it at a time?

Exactly. The "method header" synchronized keyword on static methods imposes a lock on the class itself, preventing other threads to enter.

public static synchronized void foo() {
    ...
}

is (almost) equivalent to

public static void foo() {
   synchronized(MyClass.class) {
      ...
   }
}
gaborsch
  • 15,408
  • 6
  • 37
  • 48