packagecom.codertom.params.engine;importcom.google.common.base.Strings;import org.apache.zookeeper.*;importjava.io.IOException;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.locks.Lock;/*** Zookeepr实现分布式锁*/
public classLockTest {private String zkQurom = "localhost:2181";private String lockNameSpace = "/mylock";private String nodeString = lockNameSpace + "/test1";privateLock mainLock;privateZooKeeper zk;publicLockTest(){try{
zk= new ZooKeeper(zkQurom, 6000, newWatcher() {
@Overridepublic voidprocess(WatchedEvent watchedEvent) {
System.out.println("Receive event "+watchedEvent);if(Event.KeeperState.SyncConnected ==watchedEvent.getState())
System.out.println("connection is established...");
}
});
}catch(IOException e) {
e.printStackTrace();
}
}private void ensureRootPath() throwsInterruptedException {try{if (zk.exists(lockNameSpace,true)==null){
zk.create(lockNameSpace,"".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
}
}catch(KeeperException e) {
e.printStackTrace();
}
}private void watchNode(String nodeString, final Thread thread) throwsInterruptedException {try{
zk.exists(nodeString,newWatcher() {
@Overridepublic voidprocess(WatchedEvent watchedEvent) {
System.out.println("==" +watchedEvent.toString());if(watchedEvent.getType() ==Event.EventType.NodeDeleted){
System.out.println("Threre is a Thread released Lock==============");
thread.interrupt();
}try{
zk.exists(nodeString,newWatcher() {
@Overridepublic voidprocess(WatchedEvent watchedEvent) {
System.out.println("==" +watchedEvent.toString());if(watchedEvent.getType() ==Event.EventType.NodeDeleted){
System.out.println("Threre is a Thread released Lock==============");
thread.interrupt();
}try{
zk.exists(nodeString,true);
}catch(KeeperException e) {
e.printStackTrace();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
});
}catch(KeeperException e) {
e.printStackTrace();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
});
}catch(KeeperException e) {
e.printStackTrace();
}
}/*** 获取锁
*@return*@throwsInterruptedException*/
public boolean lock() throwsInterruptedException {
String path= null;
ensureRootPath();
watchNode(nodeString,Thread.currentThread());while (true) {try{
path= zk.create(nodeString, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
}catch(KeeperException e) {
System.out.println(Thread.currentThread().getName()+ " getting Lock but can not get");try{
Thread.sleep(5000);
}catch(InterruptedException ex){
System.out.println("thread is notify");
}
}if (!Strings.nullToEmpty(path).trim().isEmpty()) {
System.out.println(Thread.currentThread().getName()+ " get Lock...");return true;
}
}
}/*** 释放锁*/
public voidunlock(){try{
zk.delete(nodeString,-1);
System.out.println("Thread.currentThread().getName() + release Lock...");
}catch(InterruptedException e) {
e.printStackTrace();
}catch(KeeperException e) {
e.printStackTrace();
}
}public static void main(String args[]) throwsInterruptedException {
ExecutorService service= Executors.newFixedThreadPool(10);for (int i = 0;i<4;i++){
service.execute(()->{
LockTest test= newLockTest();try{
test.lock();
Thread.sleep(3000);
}catch(InterruptedException e) {
e.printStackTrace();
}
test.unlock();
});
}
service.shutdown();
}
}