Zookeeper Distributed Lock Service

Source: Internet
Author: User

To develop a distributed environment mutex lock Based on zookeeper, first abstract the lock function:
Public interface lock {

/Try to get the lock, return true if success or false immediately
// Return true if this machine already hold the lock return false if zookeeper service is disable
Public Boolean trylock ();

// Release the lock and return true if success, return false if zookeeper service is disable
Public Boolean unlock ();

// Return true if currently runnable get the lock, return false if zookeeper service is disable
Public Boolean isowner ();

// Register listener to prescribed lock when currently runnable get the lock will call. dotask
// And CTX is the context, throw a runtimeexception if zookeeper service is disable
Public void registerlistener (callback call, object CTX );

}
----------------------------
A path on zookeeper corresponds to a mutex lock. For example,/lock/mutex/wdx corresponds to a mutex lock.
If you want to obtain the lock, create an instantaneous sub-node ower in this path and write your own IP address. If the lock is successfully created,
Other machines found that the path/lock/mutex/wdx/ower already exists. Then, they read the data on the node and compare it with their own IP addresses.
The lock fails to be obtained.
If you want to release the lock, first check that the path/lock/mutex/wdx/ower does not exist. If it does not exist, it means no release. If it exists, read the above
Data is compared with your own IP address. If the IP address is the same, you have the right to delete the data of this instantaneous node.
To register a listener, call the exits function of zookeeper and inject the watcher listening path/lock/mutex/wdx/ower.
When the node is called back by eventthread, the node is created, deleted, and the data is modified.

Note that the ../ower node is an instantaneous node. Therefore, if the locked machine is restarted, the node exists within a short period of time.
Nodes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.