Difference between getAndSet and compareAndSet in AtomicBoolean

前端 未结 4 1285
攒了一身酷
攒了一身酷 2021-01-04 01:00

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

  • java.u
4条回答
  •  醉酒成梦
    2021-01-04 01:25

    You can look at the code for better understanding :

    public final boolean getAndSet(boolean newValue) {
        for (;;) {
            boolean current = get();
            if (compareAndSet(current, newValue))
                return current;
        }
    }
    

    In getAndSet, if the value of the boolean has changed between the time you get() the old value and the time you try to change its value, compareAndSet won't change its value. Therefore, getAndSet calls compareAndSet in a loop until the boolean is set to the new value.

    As to your code example :

    flag.getAndSet(false) returns the old value of the AtomicBoolean. On the other hand, flag.compareAndSet(x,false) (note there are two arguments) returns whether the AtomicBoolean was modified, or in other words, it returns whether the old value of the AtomicBoolean was x.

提交回复
热议问题