Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do static methods block?

Tags:

java

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?

like image 778
Rocky Inde Avatar asked Sep 17 '13 23:09

Rocky Inde


2 Answers

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.

like image 161
dst Avatar answered Nov 07 '22 10:11

dst


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".

like image 31
Stephen C Avatar answered Nov 07 '22 09:11

Stephen C