Laboratory structure
Every instance is a watcher, when event be triggered
process method will be callback.public class SyncPrimitive implements Watcher
Properties
1
2
3
4
5
6// share zk client
static ZooKeeper zk = null;
// share lock mointor
static Integer mutex;
// instance zk path
String root;Constructor
1
2
3
4
5
6
7
8
9
10
11
12
13
14SyncPrimitive(String address) {
if(zk == null){
try {
System.out.println("Starting ZK:");
zk = new ZooKeeper(address, 3000, this);
mutex = new Integer(-1);
System.out.println("Finished starting ZK: " + zk);
} catch (IOException e) {
System.out.println(e.toString());
zk = null;
}
}
// else mutex = new Integer(-1);
}- if the common zk client not exists, create one
- create the lock monitor by the way
- if not init the propertiy mutex is 0.
Implements abstract method
1 | synchronized public void process(WatchedEvent event) { |
If the thread have monitor, call one another.
If not, wait for monitor mutex
unlock.