用java写个分布式锁
时间: 2023-05-11 08:06:39 浏览: 159
java7源码-distributed-lock:分布式锁
好的,以下是一个用 Java 实现的分布式锁的示例代码:
```java
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class DistributedLock {
private static final String LOCK_ROOT_PATH = "/locks";
private static final String LOCK_NODE_NAME = "lock_";
private static final int SESSION_TIMEOUT = 5000;
private ZooKeeper zooKeeper;
private String lockPath;
private String lockNodePath;
private CountDownLatch lockLatch;
public DistributedLock(String connectString) throws IOException, InterruptedException, KeeperException {
zooKeeper = new ZooKeeper(connectString, SESSION_TIMEOUT, null);
if (zooKeeper.exists(LOCK_ROOT_PATH, false) == null) {
zooKeeper.create(LOCK_ROOT_PATH, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
}
public void lock() throws InterruptedException, KeeperException {
lockPath = zooKeeper.create(LOCK_ROOT_PATH + "/" + LOCK_NODE_NAME, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
lockLatch = new CountDownLatch(1);
List<String> children = zooKeeper.getChildren(LOCK_ROOT_PATH, false);
Collections.sort(children);
int index = children.indexOf(lockPath.substring(LOCK_ROOT_PATH.length() + 1));
if (index == 0) {
lockLatch.countDown();
} else {
String prevNodePath = LOCK_ROOT_PATH + "/" + children.get(index - 1);
zooKeeper.exists(prevNodePath, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeDeleted) {
lockLatch.countDown();
}
}
});
lockLatch.await();
}
}
public void unlock() throws InterruptedException, KeeperException {
zooKeeper.delete(lockPath, -1);
zooKeeper.close();
}
}
```
这个分布式锁使用 ZooKeeper 实现,每个锁都是一个临时顺序节点,当一个线程需要获取锁时,它会创建一个临时顺序节点,并获取所有锁节点的子节点列表,然后将自己的节点插入到列表中,并按照节点名称排序。如果自己的节点是列表中的第一个节点,那么它就获得了锁;否则,它就需要监视前一个节点的删除事件,一旦前一个节点被删除,它就可以获得锁了。
如果您有任何问题,请随时问我。
阅读全文