[concurrency-interest] Question on compareAndSet

David Holmes davidcholmes at aapt.net.au
Wed Nov 18 00:36:00 EST 2009


You can build a lock out of compareAndSet - though to do it properly (no
busy-waiting, no time-based polling) you also need LockSupport.park. See how
ReentrantLock is implemented in terms of AbstractQueuedSynchronizer.

But the CAS documentation was not referring to the ability to build locks
out of CAS.

Cheers,
David
  -----Original Message-----
  From: raghuram nidagal [mailto:raghuram.nidagal at gmail.com]
  Sent: Wednesday, 18 November 2009 3:29 PM
  To: dholmes at ieee.org
  Cc: concurrency-interest at cs.oswego.edu
  Subject: Re: [concurrency-interest] Question on compareAndSet


  Thanks David.
  I assume compareAndSet on a single variable by itself can be used to
provide locking functionality though..
  while(notDone){
  if(x.compareAndSet(true,false)){
  //do something
  notDone=false;
  x.set(false);
  }
  else{
  sleep..
  }
  }
  is that different from synchronized except that this code does not block
trying to acquire the lock whereas synchronized would block ?

  On Wed, Nov 18, 2009 at 10:14 AM, David Holmes <davidcholmes at aapt.net.au>
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.

    HTH

    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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20091118/b786af79/attachment-0001.html>


More information about the Concurrency-interest mailing list