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 ?
In your second example, local is not exactly local, because you are not declaring it inside met1. Probably you meant:
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.