Reputation: 4020
I have a doubt on the java synchronization mechanism. Let us take the following piece of code--
class A {
int instance=0;
synchronized void met1() {
instance=instance +1;
....
instance = instance+2*3;
}
In the above method met1, we need to make it synchronized in a multi threaded enviroment because it is modifying an instance variable of an object. However in this piece of code --
class A {
synchronized void met1() {
local=local +1;
....
local = local+2*3;
}
The method met1 is modifying a local variable, which I think will be unique for each thread that executes that method. So in this case, when a thread is modifying only a local variable, is it necessary to make the method synchronized ?
Upvotes: 0
Views: 172
Reputation: 62439
In your second example, local is not exactly local, because you are not declaring it inside met1. Probably you meant:
synchronized void met1() {
int local = 0;
// ...
local=local +1;
....
local = local+2*3;
}
Then yes, you are correct, since each method call happens on the stack of the calling thread, method-local variables exist only the corresponding thread's stack and don't need synchronized access.
Upvotes: 0
Reputation: 5533
You don't need to worry about local variables in multi threaded environment. You don't need to make it synchronized . But In your code the variable "local" is not defined as local variable in met1().
Upvotes: 0
Reputation: 16037
Nope, is is not necessary to sync a method which , only modifies local variables and does not alter the state of objects
Upvotes: 0
Reputation: 691735
No. If the method only modifies local variables and method arguments, you don't need to synchronize the method. The more stateless and immutable your classes are, the less synchronization you need.
Upvotes: 0
Reputation: 12439
No, if a method defines and uses variables in local scope only, you don't need to synchronize it. You only need to synchronize those methods which either change or provide access to mutable state.
Java concurrency rules are more complicated than you might think and there are plenty of gotchas so it's well worth reading up on the intricacies. "Java Concurrency in Practice" by Goetz et al is pretty good (and is basically from the horses mouth).
Upvotes: 0
Reputation: 14346
Not if the variable is truly method-local -- however, your example code doesn't actually show the local declaration! So don't spread this example around...
Upvotes: 0
Reputation: 185852
Assuming the variable is declared inside met1
, no, you don't need synchronized
.
Upvotes: 3