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?
You want to build a, or use an existing, semaphore.
This has a better answer.