Search code examples
javaconcurrencyatomiccompare-and-swap

If compareAndSet fails, is the code below still executed?


I have a very dumb question. If I use AtomicReferences compareAndSet this way

    original.set(atomic.get());
    long next = some new value
    atomic.compareAndSet(original.get(), next);
    ....more code....

is more code still updated if the comparison fails (i.e. atomic has been updated by another thread). I'm trying to find an error in an assignment and this is the only thing I can think about and I've been trying for few hours.

P.S. Weirdly enough, if I use synchronize on this code it gives me the correct answer on my laptop, but not on my desktop


Solution

  • MangatRaiModi and SotiriosDelimanolis put me on the right path. A simple fix:

        original.set(atomic.get());
        long next = some new value
        while(!atomic.compareAndSet(original.get(), next))
        {
          do above again
        }
        ....more code....
    

    did it. Still not sure how synchronized fixed this on my laptop but not on my desktop. I'm guessing that it's slowing the threads down on the mobile Chip enough so that they can operate sequentially (Like a Print statement). I'm probably wrong though.