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 count = 0;

  public void count() {
    int count = this.count;
    int limit = count + 100;
    while (count++ != limit) System.out.println(count); 
  }

}

Note how the local variable count shadows the field count, and how the this keyword is used to refer to the field count 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 {

  private int count = 0;

  public void count() {
    int count = this.count;
    int limit = count + 100;
    while (count++ != limit) System.out.println(count);
    this.count = count; 
  }

}

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 | Cafe au Lait

Copyright 1997, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 18, 2002