记一次 "排它锁" 和 "自旋锁" 的简单实现

记一次排它锁自旋锁的简单实现

  • 定义一个lock接口

    public interface PutMessageLock {
        void lock();
    
        void unlock();
    }
    
  • 排它锁实现

    • 使用java自带的 ReentrantLock即可
    public class PutMessageReentrantLock implements PutMessageLock {
        private ReentrantLock putMessageNormalLock = new ReentrantLock(); // NonfairSync
    
        @Override
        public void lock() {
            putMessageNormalLock.lock();
        }
    
        @Override
        public void unlock() {
            putMessageNormalLock.unlock();
        }
    }
    
  • 自旋锁实现

    • 使用 cas + 循环 来实现
    public class PutMessageSpinLock implements PutMessageLock {
        //true: Can lock, false : in lock.
        private AtomicBoolean putMessageSpinLock = new AtomicBoolean(true);
    
        @Override
        public void lock() {
            boolean flag;
            do {
                flag = this.putMessageSpinLock.compareAndSet(true, false);
            }
            while (!flag);
        }
    
        @Override
        public void unlock() {
            this.putMessageSpinLock.compareAndSet(false, true);
        }
    }
    

----------------------------------------- 广告时间 -----------------------------------------

各位看官,  欢迎关注公众号,每天推送有意思的小东西哦!!!

你可能感兴趣的:(java)