zookeeper 分布式锁 java_Zookeeper实现分布式锁

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值