1

I want to implement a mutex in Java using atomic variables. I tried implementing 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?

Boolean
  • 14,266
  • 30
  • 88
  • 129
  • 1
    Is this just an exercise? Java has [built-in concurrency](http://download.oracle.com/javase/tutorial/essential/concurrency/index.html) for use in production code. – Matt Ball Feb 08 '11 at 21:25
  • 2
    @Matt Ball: I like comments not answering the question. (which could be rephrased as *"Since when did SO become a place where you question the question instead of answering the question?"*) – SyntaxT3rr0r Feb 08 '11 at 22:41
  • 2
    His comment could easily be parsed as "You may be going about this the wrong way by implementing it yourself, depending on what you goals are. If all you're after is an implementation to use, Java has this type of functionality built into it's standard library". – RHSeeger Feb 09 '11 at 15:41

2 Answers2

2

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.

Jed Wesley-Smith
  • 4,686
  • 18
  • 20
1

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

This has a better answer.

Community
  • 1
  • 1
aqua
  • 3,269
  • 28
  • 41