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.