ZooKeeper distributed lock implementation principle

principle

When a process needs to access shared data, it creates a subnode of sequence type under the "/locks" node, called thisPath. When thisPath is the smallest among all subnodes, it means that the process has acquired the lock. After the process acquires the lock, it will The shared resource can be accessed. After the access is completed, thisPath needs to be deleted. The lock is obtained by the new smallest child node.

How does the process know that thisPath is the smallest of all child nodes? You can get the list of child nodes through the getChildren method at the time of creation, and then find the node ranked first than thisPath in the list, called waitPath, and then register it on waitPath Listen, when waitPath is deleted, the process is notified, which means that the process has acquired the lock.

lock operation process:

1. Create a permanent node as the root directory of the lock

2. When a lock is to be acquired, a temporary ordered node is created in the lock directory

3. Check whether the child nodes of the lock directory have a sequence smaller than it, and if so, listen to the previous node smaller than it, and the current lock is in a waiting state

4. When the waiting time exceeds the connection time (sessionTimeout) of the Zookeeper session, the current session expires, and Zookeeper automatically deletes the temporary node created by this session, waits for the end of the state, and fails to acquire the lock

5. When the listener is triggered, the wait state ends and the lock is acquired

unlock operation process:

You can delete the node corresponding to your own id, and the corresponding next queued node can receive the Watcher event, which will be woken up to get the lock and then exit;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325024760&siteId=291194637