Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

java - Difference between getAndSet and compareAndSet in AtomicBoolean

The thread title should be self-explnatory... I'm a bit confused between the specification of below methos from AtomicBoolean class:

  • java.util.concurrent.atomic.AtomicBoolean#compareAndSet
  • java.util.concurrent.atomic.AtomicBoolean#getAndSet

My assemption is that both would result in the same behavior when used as a boolean clause in an if condition:

public class Test {
  private AtomicBoolean flag = AtomicBoolean(false);

  public void processSomeAction() {
    if (flag.getAndSet(false)) { // Shouldn't this be similar to flag.compareAndSet(false)
      // process some action
    }
  }
  //...
  private void internalMutatorMethod() {
    // do some staff then update the atomic flag
    flas.set(true);
  }
}

Assuming that I want to retrieve the current flag value and update it automaticlly, shouldn't both methods produce the same behavior?

I would much appreciate any explanations regarding how and when to use each of those if I'm missing internal differences.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The documentation is pretty clear.

  • getAndSet --> "Atomically sets to the given value and returns the previous value."
  • compareAndSet --> "Atomically sets the value to the given updated value if the current value == the expected value."

Not surprisingly, compareAndSet takes two arguments.

In your specific case:

  • if (flag.getAndSet(false)) will set flag to false only if its previous value was true
  • That would be the equivalent of if (flag.compareAndSet(true, false))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...