[concurrency-interest]Spinlock

David Holmes dholmes@dltech.com.au
Thu, 1 Aug 2002 11:45:57 +1000


> Sorry if this is a dumb question.  I am wondering
> if there might be something like a spinlock in
> java.util.concurrent

There may not be an actual spinlock class but the atomic compareAndSwap
operation will make it trivial to implement one:

class SpinLock {

  static final int LOCKED = 1;
  static final int UNLOCKED = 0;
  AtomicInteger lock = new AtomicInteger(UNLOCKED);

  public void acquire() {
      while (lock.compareAndSwap(UNLOCKED, LOCKED) == LOCKED)
          ; // spin
  }

  public void release() {
      lock.set(UNLOCKED);
  }

}

Gee I hope I got that right :-)

Under a "quality" implementation the above will reduce to what you would
expect/hope.

David Holmes