Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: modified addition example

...

In this noncompliant code example, the setValues() method may be invoked by multiple threads to set the a and b fields. Because this class does not test for integer overflow, a user of the Adder class must ensure that the arguments to the setValues() can be added without overflow (see INT00-J. Perform explicit range checking to ensure integer operations do not overflow for more information.

Code Block
bgColor#FFcccc
final class Adder {
  private int a;
  private int b;

  public int getSum() {
    return a + b;
  }

  public void setValues(int a, int b) {
    this.a = a;
    this.b = b;
  }
}

The getSum() contains a data race. For example, if a and b currently have the value 0values 0 and Integer.MAX_VALUE respectively, and one thread calls getSum() while another calls setValues(1, 1Integer.MAX_VALUE, 0), then getSum() might return 0, 1Integer.MAX_VALUE, or 2. The value 1 is returned overflow and wrap. Overflow will occur when the first thread reads a and b, after the second thread has set the value of a to Integer.MAX_VALUE but before it has set the value of b to 0.

Note that declaring the variables as volatile does not resolve the issue because these compound operations involve reads and writes of multiple variables. This code also fails to prevent integer overflow. See INT00-J. Perform explicit range checking to ensure integer operations do not overflow for more information.

Noncompliant Code Example (overflow check, atomic integer fields)

...