开发者

Implement a mutex in Java using atomic variables

开发者 https://www.devze.com 2023-02-09 03:10 出处:网络
I want to implement a mutex in Java using atomic variables. I tried i开发者_Go百科mplementing it using lamport bakery algorithm and it works. But I am not sure how to implement it, if I don\'t know th

I want to implement a mutex in Java using atomic variables. I tried i开发者_Go百科mplementing it using lamport bakery algorithm and it works. But I am not sure how to implement it, if I don't know the number of threads before.

Also, lamport algorithm keeps on increasing the labels and there is going to be an overflow, how to avoid this?


Creating a simple TTAS (test, test and set) spin-lock is fairly trivial:

class TTASLock {
  private final AtomicLong thread = new AtomicLong();

  void lock() {
    while (true) {
      if (thread.get() == 0) { // test
        if (thread.compareAndSet(0, Thread.currentThread().getId())) // testAndSet
          return;
      }
    }
  }

  void unlock() {
    thread.compareAndSet(Thread.currentThread().getId(), 0)
  }
}

This is a very simple spin-lock. The test, test and set paradigm is not strictly necessary from a logical pov, but is a critical performance improvement so that under contention a thread awaiting lock acquisition is not continually invalidating the Level2 cache line with failed CAS ops.


You want to build a, or use an existing, semaphore.

This has a better answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消