記一次排它鎖
和自旋鎖
的簡單實現
-
定義一個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); } } 複製程式碼
- 使用