Thanks Aleksey, for the usual convincing benchmark result. You win! I can imagine a machine that has a native cas instruction, but no native exchange instruction, but no one ever got fired for optimizing for x86.
public final boolean getAndSet(boolean newValue) { return (int)VALUE.getAndSet(this, (newValue ? 1 : 0)) != 0; } On Thu, Aug 11, 2016 at 1:08 PM, Aleksey Shipilev < aleksey.shipi...@gmail.com> wrote: > On 08/11/2016 09:59 PM, Martin Buchholz wrote: > > On Thu, Aug 11, 2016 at 10:40 AM, Aleksey Shipilev > >> Why doesn't AtomicBoolean.getAndSet use VarHandle.getAndSet, which is > >> hopefully intrinsified completely? > > > > Good question. This optimization originated in a suggestion for jdk8, > > where there are no VarHandles. > > VarHandle.getAndSet does not know there are only two values for the int, > > so it is not obvious which one wins. I can imagine getAndSet being > > compiled to a weak cas loop. > > getAndSet/getAndAdd have a nice rationale for x86: they compile to > xchg/xadd, respectively. This is what I meant about "intrinsified > completely". > > >> Any benchmarks backing up this optimization? > > > > I measured a reduction in bytecode! Does that count? > > I measured x86 instructions count, and you would not believe what it > told me! > http://cr.openjdk.java.net/~shade/8162805/BooleanGetAndSet.java > > Thanks, > -Aleksey > >