[concurrency-interest] Question on compareAndSet

David Holmes davidcholmes at aapt.net.au
Tue Nov 17 23:44:51 EST 2009

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
  Sent: Wednesday, 18 November 2009 2:34 PM
  To: concurrency-interest at cs.oswego.edu
  Subject: [concurrency-interest] Question on compareAndSet

  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?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20091118/fa92f550/attachment.html>

More information about the Concurrency-interest mailing list