[concurrency-interest] Question on compareAndSet

Jed Wesley-Smith jed at atlassian.com
Wed Nov 18 23:07:24 EST 2009

You can though get atomic updates by making a composite value for the 
point (by value I mean an immutable class of immutable members) and 
using that. To reuse the example:

class Point {
  final AtomicReference<Location> location = new 
AtomicReference<Location>(new Location(0, 0));
  boolean move(Location from, Location to) {
    return location.compareAndSet(from, to);
  Location at() {return location.get();}

class Location {
  final int x, y;
  Location(final int x, final int y) {
    this.x = x;
    this.y = y;

(of course, Point should really be immutable anyway, Things move around 
from point to point, but that's another topic entirely, see Are we there 
yet from Rich Hickey: 
http://www.infoq.com/presentations/Are-We-There-Yet-Rich-Hickey or, 
there is no such thing as a mutable value!


David Holmes wrote:
> Hi Raghu,
> compareAndSet can only update a single variable, whereas locking can 
> enforce an atomic action over as many variables as you like. Using 
> multiple compareAndSets across different variables does not give you 
> atomicity over the set actions.
> For example suppose you have a class Point:
>   class Point {
>      int x, y;
>      void move(int newX, int newY) {
>        x = newX;
>        y = newY;
>      }
>   }
> For move(a,b) to be an atomic operation you need to use locking - eg 
> synchronize the move() method. If you instead tried to do seperate CAS 
> operations on x and y, you could end up with an x from one move() and 
> a y from a distinct move() and that would violate the property of the 
> Point, that it can only exist in an x,y position to which it has been 
> moved.
> David Holmes   
>     -----Original Message-----
>     *From:* concurrency-interest-bounces at cs.oswego.edu
>     [mailto:concurrency-interest-bounces at cs.oswego.edu]*On Behalf Of
>     *raghuram nidagal
>     *Sent:* Wednesday, 18 November 2009 2:34 PM
>     *To:* concurrency-interest at cs.oswego.edu
>     *Subject:* [concurrency-interest] Question on compareAndSet
>     Hi,
>     The documentation says "The compareAndSet method is not a general
>     replacement for locking. It applies only when critical updates for
>     an object are confined to a/ single/ variable"
>     Can someone explain what this means? What are the scenarios where
>     compareAndSet cannot be used for locking?
>     Thanks
>     Raghu
> ------------------------------------------------------------------------
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest

More information about the Concurrency-interest mailing list