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?
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With