日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Curator实现分布式锁的基本原理-LockInternals.internalLockLoop

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

?

總結

以上是生活随笔為你收集整理的Curator实现分布式锁的基本原理-LockInternals.internalLockLoop的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。