Hi, I am attempting to use the WriteLock recipe provided with ZK 3.3.2. Unfortunately, I seem to be deadlocking when I try to lock from multiple threads. If I lock sequentially, I have no trouble. Can somebody let me know what I am doing wrong here? I am attaching some sample code; I can also provide a complete maven project to test if necessary. (For the record, I have increased maxClientCnxns in my zoo.cfg to 100.)
Here we see the results without threading: $ time java -cp "lib/*" Test nothread […] finished 9 real 0m1.361s user 0m0.380s sys 0m0.050s And here is the threaded version: $ time java -cp "lib/*" Test thread finished 9 finished 8 finished 1 ^C real 3m4.627s user 0m4.600s sys 0m2.060s On the other hand, it does not always deadlock: $ time java -cp "lib/*" Test thread finished 4 finished 0 finished 3 finished 5 finished 6 finished 7 finished 2 finished 1 finished 8 finished 9 real 0m7.824s user 0m1.030s sys 0m0.170s Thanks for any help you can provide! best, Erik Hetzner
import java.util.*;
import org.apache.zookeeper.*;
import java.lang.Math;
import org.apache.zookeeper.recipes.lock.*;
import java.io.IOException;
public class Test {
public static class Ignorer implements Watcher {
public void process(WatchedEvent event){}
}
public static void lockTest (int i) {
try {
ZooKeeper zk = new ZooKeeper("localhost:2181", 10000,
new Ignorer());
WriteLock lock = new WriteLock(zk, "/testLocker/mytest", null);
lock.lock();
while (!lock.isOwner()) {
Thread.sleep(Math.round(Math.random() * 10));
}
lock.unlock();
System.err.println(String.format("finished %d", i));
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
public static class MyThread extends Thread {
int i;
public MyThread (int i) {
this.i = i;
}
public void run () {
lockTest(this.i);
}
}
public static void main (String[] args) throws InterruptedException {
if (args.length > 0 && args[0].equals("thread")) {
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0 ; i < 10 ; i++) {
Thread thread = new MyThread(i);
threads.add(thread);
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
t.join();
}
} else {
for (int i = 0 ; i < 10 ; i++) {
lockTest(i);
}
}
}
}Sent from my free software system <http://fsf.org/>.
pgpyIfYSJjFtF.pgp
Description: PGP signature
