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?
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?
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) {
...
}
}