记一次排它锁
和自旋锁
的简单实现
-
定义一个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(); } }
- 使用java自带的
-
自旋锁实现
- 使用
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); } }
- 使用
----------------------------------------- 广告时间 -----------------------------------------
各位看官, 欢迎关注公众号,每天推送有意思的小东西哦!!!
来源:oschina
链接:https://my.oschina.net/u/4136530/blog/3212680