Do different threads accessing method "foo" have their own copy of local variables, or it is needed to make this method synchronized?
class X {
static returnType foo( Object arg) {
Object localvar;
// perform some calculation based on localvar and arg.
// no non-local variable is used i.e: this is a utility method.
// return something.
}
}
If it's not using any shared state (e.g. it's really just computing something based on its parameters) then it doesn't need to be synchronized at all.
In Java, a static synchronised method is also a technique of synchronising a method so that no two threads can act on the synchronised method simultaneously. The only change is that Static Synchronised is used.
Thread synchronization is the concurrent execution of two or more threads that share critical resources. Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts may arise when parallel-running threads attempt to modify a common variable at the same time.
Putting code in a private method invites letting it be called by other methods, so it would make sense to make the private method synchronized in case in the future it is called from another method that does not otherwise need to be synchronized.
You don't need to synchronize that method. The local variable gets created in the current thread's "memory space" and there is no way that it will get accessed by any other thread (from what you've shown above).
Since the variables used are defined/used in it's own scope there is no need for syncronize the method.
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