当前位置:网站首页>Code analysis of distributed lock principle using ZK
Code analysis of distributed lock principle using ZK
2022-04-21 07:16:00 【So you're lucky】
- Main principle :
Create a temporary with serial number node, And get it , It's called nowNode
Get entire parent node All son node
if nowNode Son node One of the first , It is considered that it has successfully obtained the lock
If not the first , Prove that another thread has registered the lock in front of it , So turn on the last one that monitors it node
ask : How do you know nowNode It's the number one
Strings with ordinal numbers can also be sorted , Sort the obtained sub list , You can know the number of
Here is the code for implementation , Mainly used to help understand ideas , In the course b Standing in Silicon Valley
import org.apache.zookeeper.*;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/** * @author lyb * @Date: Founded in 18:09 2021/9/26 * @ explain : */
public class ZkLocks {
/** * zk client */
private final ZooKeeper ZK;
/** * zk The node passed in by the user , You can also write dead , Mainly understanding the principle */
private final String node;
/** * Last node , Mainly used for monitoring , On function callback , Release await */
private String lastNode;
private final CountDownLatch countDownLatch = new CountDownLatch(1);
private final CountDownLatch waitDownLatch = new CountDownLatch(1);
/** * Current node */
private String nowNode;
public ZkLocks(String iP, String node) throws Exception {
ZK = new ZooKeeper(iP, 10000, new TestWatcher());
if (node.isEmpty()) {
node = "/";
} else if (!node.startsWith("/")) {
node = "/" + node;
}
this.node = node;
// wait for zk Successful connection
countDownLatch.await();
// Judge zk Does the path exist
if (ZK.exists(node, false) == null) {
// non-existent , Then create the root node
ZK.create(node, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
}
public void getLock() throws Exception {
// Create a temporary node with sequence number , The serial number is incremented by atoms , Can sort
nowNode = ZK.create(node + "/locks-", null,
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
List<String> childrenList = ZK.getChildren(node, false);
if (childrenList.size() == 1) return;
// Prioritize
Collections.sort(childrenList);
int index = childrenList.indexOf(nowNode.split("/")[2]);
if (index == -1) {
throw new Exception(" Node error ");
}
// Is the first
if (index == 0) {
return;
}
// Listen for changes in the previous node
lastNode = node + "/" + childrenList.get(index - 1);
ZK.getData(lastNode, true, null);
waitDownLatch.await();
}
void unLock() {
try {
ZK.delete(nowNode, -1);
} catch (InterruptedException | KeeperException e) {
e.printStackTrace();
}
}
class TestWatcher implements Watcher {
@Override
public void process(WatchedEvent watchedEvent) {
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
countDownLatch.countDown();
}
if (watchedEvent.getType() == Event.EventType.NodeDeleted &&
watchedEvent.getPath().equals(lastNode)) {
waitDownLatch.countDown();
}
}
}
}
Test class
/** * @author lyb * @Date: Founded in 19:07 2021/9/26 * @ explain : */
public class ZkLockTest {
public static void main(String[] args) throws Exception {
final ZkLocks locks1 = new ZkLocks("127.0.0.1:2181", "/locksTest");
final ZkLocks locks2 = new ZkLocks("127.0.0.1:2181", "/locksTest");
System.out.println(" Connection complete ");
new Thread(() -> {
try {
locks1.getLock();
System.out.println(" Threads 1 Get lock ");
Thread.sleep(3000);
System.out.println(" Threads 1 Release the lock ");
locks1.unLock();
} catch (Exception e) {
}
}).start();
new Thread(() -> {
try {
locks2.getLock();
System.out.println(" Threads 2 Get lock ");
Thread.sleep(3000);
System.out.println(" Threads 2 Release the lock ");
locks2.unLock();
} catch (Exception e) {
}
}).start();
Thread.sleep(1000000000);
}
}
版权声明
本文为[So you're lucky]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210615360571.html
边栏推荐
- 跨域问题-Allow-Origin header contains multiple values... but only one is allowed
- grub boot.S代码分析
- TP下载文件夹,压缩文件夹并下载
- [ksz8863] information summary and board verification results of ksz8863 switch chip
- If I use Monet's color matching in scientific research pictures?
- 记录tx2上安装配置gestermer进而使用gst-rtsp-server
- 数据异构方案
- Learn SCI paper drawing skills (c)
- 3-1.pod控制器
- CF1427C The Hard Work of Paparazzi题解
猜你喜欢

将在CSDN中写好的文章导出为pdf格式

applicationContext.xml变成灰色的文档咋解决

开放平台及其技术架构

STM32 H743 ECC内存相关使用说明笔记
![[AD] modular schematic drawing pit point record](/img/b3/02136b8f9193d87a4780dd131f5d35.png)
[AD] modular schematic drawing pit point record
![[LabVIEW] record some pits in LabVIEW project](/img/88/5556dd887d54f11bbc3afc9dfce25e.png)
[LabVIEW] record some pits in LabVIEW project

Chapter 5 support vector machine (SVM)

Error when Linux starts MySQL

applicationContext. How to solve the problem of XML becoming gray document

Tensorflow case 4: MNIST handwritten numeral recognition (linear neural network) and its limitations
随机推荐
搭建自己的blog
[STM32] cubemx configuration diagram of 480mhz clock under 25MHz external crystal oscillator of h743
3. Date command problem in bat
Busybox initrd及初始化流程
【STM32】H743的25MHZ外部晶振下480MHz时钟的CubeMX配置图
【ThreadX】ThreadX源碼閱讀計劃(二)
记一次mySQL慢sql优化
SQL--数据定义
2021年YCU蓝桥杯程序设计竞赛选拔赛题解
微信小程序request封装
导jstl标签库uri没有提示
6 service and ingress
程序员也可以写小说
IDE常用快捷键
Program download and data extraction using JLINK command line
JDBC simple implementation of student management system
mysql与oracle的区别小总结
完全清理mysql-win
[threadx] threadx source Reading plan (II)
毕业设计,课程环节学生成绩评价系统