Synchronization: another solution

A somewhat more general solution that combines the previous two is to copy the value of the field into a local variable, then change only the local variable. The field remains unchanged inside the method. For example,

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.


Previous | Next | Top
Last Modified December 2, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu