Synchronization on arguments of static methods

2020-07-26 11:07发布

问题:

I have a question concerning the java synchronization with static methods.

More precisely, I have a class with static methods that can be used concurrently by several threads. The principal static method of my class has one argument and calls the other auxiliary static methods one after the other passing them this argument.

My question is the following: since the class can be used by multiple threads at a time, isn't there a risk that another thread replaces the argument by another one?

I had thought of using a synchronization block on the argument variable of my principal function encompassing the whole code of the method (and thus the calls to auxiliary functions too), but I'm not sure it is a good solution.

Could anyone help me?

回答1:

My question is the following: since the class can be used by multiple threads at a time, isn't there a risk that another thread replaces the argument by another one?

No there isn't. You are confusing static and stack storage.

 static int x;

 static void someMethod(int y1, SomeObject y2) {
     int z;
     ...
 }

In a threaded situation, all threads access the same field x. You need to worry about synchronization of that field. However, even though someMethod(...) is a static method, the y1 argument and the z method field are local to the calling threads. Other threads can't access that memory since its on the thread's call stack.

The exception to this is the argument y2 since it is an object. Java is pass by value and primitives are passed on the stack. However when you pass an object by value, you pass its reference so two threads could get passed the same object reference and you would need to worry about synchronization there.

As an aside, calling static methods between threads although certainly allowed is not the best pattern. Instances are the way to go if possible. They can share static constant fields and the like but calling various static methods from other static methods sounds overly confusing.



回答2:

I don't think it is possible for the value of the argument to be "replaced" by another thread... threads have their own method context... the so-called call-stack. For example, you could have 50 threads calling String.valueOf() at the same exact time for different values, and each would get the value that is within their own thread context.