Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concurrent access to static methods in java, is synchronization needed?

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.
   }
}
like image 887
Navid Avatar asked Aug 16 '11 17:08

Navid


People also ask

Do we need to synchronize static methods?

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.

Is static function a synchronization mechanism?

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.

When would thread synchronization is needed?

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.

Is it necessary to synchronize on private methods?

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.


2 Answers

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

like image 148
Kiril Avatar answered Sep 23 '22 02:09

Kiril


Since the variables used are defined/used in it's own scope there is no need for syncronize the method.

like image 42
lgtelles Avatar answered Sep 22 '22 02:09

lgtelles