Skip to content

Instantly share code, notes, and snippets.

@huahang
Created April 9, 2015 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huahang/e6ebf948804fd7ea7c13 to your computer and use it in GitHub Desktop.
Save huahang/e6ebf948804fd7ea7c13 to your computer and use it in GitHub Desktop.
2 clients aquired the same InterProcessLock?
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MutexExample {
private static String zkServerList = "zookeeper_host:2181";
private static String zkLockPath = "/sandbox/lock";
private static ExecutorService executorService = Executors.newFixedThreadPool(100);
public static void loop(Runnable runnable) {
for (Integer i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; ++i) {
if (null != runnable) {
runnable.run();
}
}
}
public static void endlessLoop() {
loop(new Runnable() {
public void run() {
loop(new Runnable() {
public void run() {
loop(new Runnable() {
public void run() {
loop(new Runnable() {
public void run() {
loop(new Runnable() {
public void run() {
loop(new Runnable() {
public void run() {
loop(null);
}
});
}
});
}
});
}
});
}
});
}
});
}
public static void main(String[] args) throws InterruptedException {
final CuratorFramework client = CuratorFrameworkFactory.newClient(
zkServerList,
new ExponentialBackoffRetry(1000, 3)
);
client.start();
for (int i = 0; i < 2; ++i) {
final int clientID = i;
executorService.submit(new Runnable() {
public void run() {
InterProcessLock lock = new InterProcessMutex(client, zkLockPath);
try {
System.out.println("Client #" + clientID + " trying to acquire lock");
lock.acquire();
System.out.println("Client #" + clientID + " lock acquired");
endlessLoop();
lock.release();
System.out.println("Client #" + clientID + " lock released");
} catch (Throwable t) {
t.printStackTrace();
}
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment