Navid
Navid

Reputation: 701

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

Upvotes: 5

Views: 4541

Answers (3)

VirtualTroll
VirtualTroll

Reputation: 3091

The method should not be synchronized but you should use a final variable arg ie
static returnType foo(final Object arg).

Upvotes: 0

Kiril
Kiril

Reputation: 40395

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

Upvotes: 15

lgtelles
lgtelles

Reputation: 41

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

Upvotes: 1

Related Questions