Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.atomic.AtomicLong;
- public class ReentrantCASLock {
- private AtomicLong lockingThread;
- private int count;
- public ReentrantCASLock() {
- lockingThread = new AtomicLong(-1);
- count = 0;
- }
- public void lock() {
- while (!(lockingThread.compareAndSet(-1, Thread.currentThread().getId())
- || lockingThread.compareAndSet(Thread.currentThread().getId(), Thread.currentThread().getId())));
- count++;
- }
- public void unlock() throws IllegalMonitorStateException {
- if (lockingThread.get() != Thread.currentThread().getId()) {
- throw new IllegalMonitorStateException();
- }
- count--;
- if (count == 0) {
- while (lockingThread.compareAndSet(Thread.currentThread().getId(), -1));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement