public class Counter {
int i = 0;
public void count() {
int i = this.i;
int limit = i + 100;
while (i++ != limit) System.out.println(i);
}
}
Note how the local variable i
shadows the field i
, and how the this keyword is used to refer to the field i
outside the shadow.This trick is primarily useful when you don't need to save the changed variable back into the field when the method is done. The following saves the state, but is still subject to less obvious synchronization problems.
public class Counter {
int i = 0;
public void count() {
int i = this.i;
int limit = i + 100;
while (i++ != limit) System.out.println(i);
this.i = i;
}
}
In fact, this is probably even worse than the original example
because it will work 99 times out of a 100. The bug here is extremely
hard to pin down if you don't spot it in the source code.