1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
| public class ZKLockRW {
protected String lockPath;
protected CuratorFramework zkClient;
private CountDownLatch countDownLatch=new CountDownLatch(1);
private final static String WRITE_NAME="_W_LOCK";
private final static String READ_NAME="_R_LOCK";
public ZKLockRW(String lockPath, CuratorFramework client) { this.lockPath=lockPath; this.zkClient=client; }
public void lock() throws Exception { String node = createNode(); tryLock(node); countDownLatch.await(); }
private String createNode() throws Exception { return zkClient.create() .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE) .forPath(lockPath); }
public ZKLockRW writeLock(){ return new ZKLockRW(lockPath+WRITE_NAME,zkClient); }
public ZKLockRW readLock(){ return new ZKLockRW(lockPath+READ_NAME,zkClient); }
private void tryLock(String nodePath) throws Exception { List<String> childPaths = zkClient.getChildren() .forPath("/") .stream().sorted().map(o->"/"+o).collect(Collectors.toList());
if (nodePath.equals(childPaths.get(0))){ countDownLatch.countDown(); return; }
if (nodePath.contains(READ_NAME)){ String preNode = getNearWriteNode(childPaths, childPaths.indexOf(nodePath)); if (preNode==null){ countDownLatch.countDown(); return; } NodeCache nodeCache=new NodeCache(zkClient,preNode); nodeCache.start(); ListenerContainer<NodeCacheListener> listenable = nodeCache.getListenable(); listenable.addListener(() -> { if (nodeCache.getCurrentData()==null){ String nearWriteNode = getNearWriteNode(childPaths, childPaths.indexOf(preNode)); if (nearWriteNode==null){ countDownLatch.countDown(); return; } tryLock(nearWriteNode); } }); }
if (nodePath.contains(WRITE_NAME)){ String preNode = childPaths.get(childPaths.indexOf(nodePath) - 1); NodeCache nodeCache=new NodeCache(zkClient,preNode); nodeCache.start(); ListenerContainer<NodeCacheListener> listenable = nodeCache.getListenable(); listenable.addListener(() -> { if (nodeCache.getCurrentData()==null){ tryLock(childPaths.get(childPaths.indexOf(preNode) - 1<0?0:childPaths.indexOf(preNode) - 1)); } }); } }
private String getNearWriteNode(List<String> childPath,Integer index){ for (int i = 0; i < index; i++) { String node = childPath.get(i); if (node.contains(WRITE_NAME)) return node;
} return null; }
}
|