java 分布式锁代码
时间: 2023-07-08 08:47:32 浏览: 105
以下是基于 Zookeeper 实现的 Java 分布式锁代码示例:
```java
import org.apache.zookeeper.*;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class DistributedLock implements Watcher {
private ZooKeeper zk;
private String lockPath;
private String selfPath;
private CountDownLatch connectedSignal = new CountDownLatch(1);
private CountDownLatch lockSignal = new CountDownLatch(1);
private volatile boolean locked = false;
public DistributedLock(String hosts, String lockPath) {
try {
this.zk = new ZooKeeper(hosts, 10000, this);
this.lockPath = lockPath;
connectedSignal.await();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
public void lock() {
try {
selfPath = zk.create(lockPath + "/lock_", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
while (!locked) {
locked = tryLock();
if (!locked) {
waitForLock();
}
}
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
}
public void unlock() {
try {
zk.delete(selfPath, -1);
zk.close();
} catch (InterruptedException | KeeperException e) {
e.printStackTrace();
}
}
private boolean tryLock() throws KeeperException, InterruptedException {
boolean lockAcquired = false;
String[] children = zk.getChildren(lockPath, false).toArray(new String[0]);
sortChildren(children);
for (int i = 0; i < children.length; i++) {
if (selfPath.endsWith(children[i])) {
if (i == 0) {
lockAcquired = true;
lockSignal.countDown();
}
break;
}
}
return lockAcquired;
}
private void waitForLock() throws KeeperException, InterruptedException {
String prevNode = null;
String[] children = zk.getChildren(lockPath, false).toArray(new String[0]);
sortChildren(children);
for (int i = 0; i < children.length; i++) {
if (selfPath.endsWith(children[i])) {
prevNode = children[i - 1];
break;
}
}
if (prevNode != null) {
zk.exists(lockPath + "/" + prevNode, this);
lockSignal.await();
}
}
private void sortChildren(String[] children) {
for (int i = 0; i < children.length; i++) {
for (int j = i + 1; j < children.length; j++) {
if (compare(children[i], children[j]) > 0) {
String temp = children[i];
children[i] = children[j];
children[j] = temp;
}
}
}
}
private int compare(String s1, String s2) {
String[] arr1 = s1.split("_");
String[] arr2 = s2.split("_");
int num1 = Integer.parseInt(arr1[1]);
int num2 = Integer.parseInt(arr2[1]);
return num1 - num2;
}
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
connectedSignal.countDown();
}
if (event.getType() == Event.EventType.NodeDeleted && event.getPath().equals(lockPath + "/" + selfPath)) {
lockSignal.countDown();
}
}
}
```
使用方法:
```java
DistributedLock lock = new DistributedLock("localhost:2181", "/test");
lock.lock();
try {
// 执行临界区代码
} finally {
lock.unlock();
}
```
阅读全文