由於公司現在的架構師微服務,每個服務都需要進行分佈式部署,對於一些功能,可能就需要考慮用分佈式鎖,分佈式鎖的實現方案有很多種,爲了更升入的理解,樓主考慮深度的學習下jdk的可重入鎖ReentrantLock
打開ReentrantLock的源碼便發現 它內部實現了aqs,通過繼承aqs實現了公平鎖Sync,非公平鎖NonfairSync
說到這我介紹下什麼是aqs
aqs 是一個抽象隊列同步器,設計模式是模板模式。
核心數據結構:雙向鏈表 + state(鎖狀態)
底層操作:CAS
首先介紹以下它的設計模式,我們加鎖的時候調用 lock()方法,如下代碼
final void lock() {
acquire(1);
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
protected boolean tryAcquire(int arg) {
throw new UnsupportedOperationException();
}
通過代碼跟蹤,我們發現acquire 裏面的tryAcquire 方法並沒有實現,但定義了一個完整的流程,tryacquire 是在子類裏面實現的
我們通過跟蹤代碼來看一下 公平鎖的實現
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
final void lock() {
acquire(1);
}
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
}
}
這段代碼我們看到了我們上面提到的state, state是幹嘛用的呢?
通過設置state狀態標識鎖有沒有被佔用,當state>0 時,表示鎖被佔用,當state=0 時,表示鎖空閒,可以被獲取,state是一個全局變量,設計到可見性問題,因此我們看源碼
private volatile int state; 定義state 用了 volatile 保證可見性
我們在研究這段代碼 當state=0 時,並且當前線程在頭節點時,便可以獲取鎖,並設置新的state 狀態, compareAndSetState(0, acquires)),我們深入這個代碼
/**
* Atomically sets synchronization state to the given updated
* value if the current state value equals the expected value.
* This operation has memory semantics of a {@code volatile} read
* and write.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that the actual
* value was not equal to the expected value.
*/
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
通過這段代碼我們發現設置state 的狀態使用的就是樂觀鎖,當前值是否與預期值相同,相同就設置成功。
在acquire 方法中,當獲取鎖失敗時,我們知道一般會做持續獲取鎖,直到超時時間,纔會返回獲取鎖失敗,
那麼看下本次獲取鎖失敗後執行的方法是acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
方法,我們通過源碼來看下,源碼是如何操作的
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
通過源碼我們可以看到
- addWaiter:通過自旋CAS,將當前線程加入上面鎖的雙向鏈表(等待隊列)中。
- acquireQueued:通過自旋,判斷當前隊列節點是否可以獲取鎖。
通過上面的分析,那麼我們來分析通過reids 實現一個分佈式鎖,如何實現,以及有哪些注意事項?
我們通過對redis 設置key ,當key不存在時,可以獲取鎖,當key存在時,表示鎖已獲取,並且reids單線程操作,數據通過卡槽分佈,不存在線程安全問題。
那麼有哪些注意事項呢
1.加鎖過程必須設置過期時間,加鎖和設置過期時間過程必須是原子操作
如果沒有設置過期時間,那麼就發生死鎖,鎖永遠不能被釋放。如果加鎖後服務宕機或程序崩潰,來不及設置過期時間,同樣會發生死鎖。
2.解鎖必須是解除自己加上的鎖
試想一個這樣的場景,服務A加鎖,但執行效率非常慢,導致鎖失效後還未執行完,但這時候服務B已經拿到鎖了,這時候服務A執行完畢了去解鎖,把服務B的鎖給解掉了,其他服務C、D、E...都可以拿到鎖了,這就有問題了。加鎖的時候我們可以設置唯一value,解鎖時判斷是不是自己先前的value就行了
public class RedisLock {
/**
* 解鎖腳本,原子操作
*/
private static final String unlockScript =
"if redis.call(\"get\",KEYS[1]) == ARGV[1]\n"
+ "then\n"
+ " return redis.call(\"del\",KEYS[1])\n"
+ "else\n"
+ " return 0\n"
+ "end";
private StringRedisTemplate redisTemplate;
public RedisLock(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 加鎖,有阻塞
* @param name
* @param expire
* @param timeout
* @return
*/
public String lock(String name, long expire, long timeout){
long startTime = System.currentTimeMillis();
String token;
do{
token = tryLock(name, expire);
if(token == null) {
if((System.currentTimeMillis()-startTime) > (timeout-50))
break;
try {
Thread.sleep(50); //try 50 per sec
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
}
}while(token==null);
return token;
}
/**
* 加鎖,無阻塞
* @param name
* @param expire
* @return
*/
public String tryLock(String name, long expire) {
String token = UUID.randomUUID().toString();
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection conn = factory.getConnection();
try{
Boolean result = conn.set(name.getBytes(Charset.forName("UTF-8")), token.getBytes(Charset.forName("UTF-8")),
Expiration.from(expire, TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT);
if(result!=null && result)
return token;
}finally {
RedisConnectionUtils.releaseConnection(conn, factory);
}
return null;
}
/**
* 解鎖
* @param name
* @param token
* @return
*/
public boolean unlock(String name, String token) {
byte[][] keysAndArgs = new byte[2][];
keysAndArgs[0] = name.getBytes(Charset.forName("UTF-8"));
keysAndArgs[1] = token.getBytes(Charset.forName("UTF-8"));
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection conn = factory.getConnection();
try {
Long result = (Long)conn.scriptingCommands().eval(unlockScript.getBytes(Charset.forName("UTF-8")), ReturnType.INTEGER, 1, keysAndArgs);
if(result!=null && result>0)
return true;
}finally {
RedisConnectionUtils.releaseConnection(conn, factory);
}
return false;
}
}
參考文檔
https://www.jianshu.com/p/7b0e11a1e605
redis實現分佈式鎖