Curator实现分布式锁的基本原理-LockInternals.internalLockLoop
生活随笔
收集整理的這篇文章主要介紹了
Curator实现分布式锁的基本原理-LockInternals.internalLockLoop
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
// 循環(huán)等待來激活分布式鎖,實現(xiàn)鎖的公平性
private boolean internalLockLoop(long startMillis, Long millisToWait, String ourPath) throws Exception { // 是否已經(jīng)持有分布式鎖 boolean haveTheLock = false; // 是否需要刪除子節(jié)點 boolean doDelete = false; try { if (revocable.get() != null) { client.getData().usingWatcher(revocableWatcher).forPath(ourPath); } while ((client.getState() == CuratorFrameworkState.STARTED) && !haveTheLock) { // 獲取排序后的子節(jié)點列表 List<String> children = getSortedChildren(); // 獲取前面自己創(chuàng)建的臨時順序子節(jié)點的名稱 String sequenceNodeName = ourPath.substring(basePath.length() + 1); // 實現(xiàn)鎖的公平性的核心邏輯,看下面的分析 PredicateResults predicateResults = driver.getsTheLock(client, children , sequenceNodeName , maxLeases); if (predicateResults.getsTheLock()) { // 獲得了鎖,中斷循環(huán),繼續(xù)返回上層 haveTheLock = true; } else { // 沒有獲得到鎖,監(jiān)聽上一臨時順序節(jié)點 String previousSequencePath = basePath + "/" + predicateResults.getPathToWatch(); synchronized (this) { try { // exists()會導致導致資源泄漏,因此exists()可以監(jiān)聽不存在的ZNode,因此采用getData() // 上一臨時順序節(jié)點如果被刪除,會喚醒當前線程繼續(xù)競爭鎖,正常情況下能直接獲得鎖,因為鎖是公平的 client.getData().usingWatcher(watcher).forPath(previousSequencePath); if (millisToWait != null) { millisToWait -= (System.currentTimeMillis() - startMillis); startMillis = System.currentTimeMillis(); if (millisToWait <= 0) { doDelete = true; // 獲取鎖超時,標記刪除之前創(chuàng)建的臨時順序節(jié)點 break; } wait(millisToWait);// 等待被喚醒,限時等待 } else { wait(); // 等待被喚醒,無限等待 } } catch (KeeperException.NoNodeException e) { // 容錯處理,邏輯稍微有點繞,可跳過,不影響主邏輯的理解 // client.getData()可能調(diào)用時拋出NoNodeException,原因可能是鎖被釋放或會話過期(連接丟失)等 // 這里并沒有做任何處理,因為外層是while循環(huán),再次執(zhí)行driver.getsTheLock時會調(diào)用validateOurIndex // 此時會拋出NoNodeException,從而進入下面的catch和finally邏輯,重新拋出上層嘗試重試獲取鎖并刪除臨時順序節(jié)點 } } } } } catch (Exception e) { ThreadUtils.checkInterrupted(e); // 標記刪除,在finally刪除之前創(chuàng)建的臨時順序節(jié)點(后臺不斷嘗試) doDelete = true; // 重新拋出,嘗試重新獲取鎖 throw e; } finally { if (doDelete) { deleteOurPath(ourPath); } } return haveTheLock;
}
?
總結
以上是生活随笔為你收集整理的Curator实现分布式锁的基本原理-LockInternals.internalLockLoop的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Curator实现分布式锁的基本原理-c
- 下一篇: Curator实现分布式锁的基本原理-g