Reputation: 1531
Let's say I have a class defined as:
public class MyClass {
private static int data;
public static staticMethod(int val){
... do something with data based on val ...
}
}
And now let's say I have many Java threads running in my application that make calls to the static method
MyClass.staticMethod(int)
Will the method block upon each invocation? i.e., if thread 1 calls the method first and while that run of the method is being executed, thread 2 calls the static method, will the second thread have to wait until the first execution is completed?
If the answer is no, then when would it make sense to use static data members in a un-"synchronized" way?
Upvotes: 7
Views: 1605
Reputation: 719307
Will the method block upon each invocation?
No. A plain static
method doesn't block other threads. (But a static synchronized
method can block other threads ... or be blocked by other threads.)
If the answer is no, then when would it make sense to use static data members in a un-"synchronized" way?
It is OK if the data member if the member is volatile
... modulo the limits of volatile.
It is OK if the data member is a final
reference to an thread-safe type.
It is OK if the data member is thread confined. (This is unlikely since the member is visible to all threads by virtue of being static
. But it is possible.)
It is OK if something else is taking care of synchronization, or if you are using Lock
objects for mutual exclusion, etcetera ... though you probably would say that these "don't count".
Upvotes: 6
Reputation: 23503
No, not unless the class/method is declare Synchronized
.
http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
Upvotes: 0
Reputation: 178303
As you have written it, no. Multiple threads will not block until another thread has finished the method execution. This is true regardless of whether the method is static
.
To enforce that only a single thread has access to the method, you must make the method synchronized
.
public static synchronized staticMethod(){
Upvotes: 4
Reputation: 3337
No, that is not part of the static
keyword. If you want to synchronize two threads accessing the same method, use other possibilities, such as synchronized
(method or statement), or stuff from the java.util.concurrent
package.
Upvotes: 8