Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: edited text

...

Code Block
bgColor#ccccff
import java.util.concurrent.atomic.AtomicBoolean;

final class Flag {
  private AtomicBoolean flag = new AtomicBoolean(true);
 
  public void toggle() { 
    boolean temp;
    do {
      temp = flag.get();
    } while(!flag.compareAndSet(temp, !temp));
  }

  public AtomicBoolean getFlag() { 
    return flag;
  }
}

This ensures that updates to the variable are carried out The flag variable is updated using the compareAndSet() method of class AtomicBoolean. All updates are made visible to other threads.

...

In this noncompliant code example, the two fields a and b setValues() method may be set invoked by multiple threads , using the setValues() method.to set the a and b fields,

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() method may return a different sum every time it is invoked from different threads. For instance contains a data race. For example, if a and b currently have the value 0, and one thread calls getSum() while another calls setValues(1, 1), then getSum() might return 0, 1, or 2. Of these, the The value 1 is unacceptable; it is returned when the first thread reads a and b, after the second thread has set the value of a but before it has set the value of b.

...

The issues described in the previous noncompliant code example can also arise occur when the fields a and b of type int are replaced with atomic integers.

...