Created
April 9, 2015 07:07
-
-
Save huahang/e6ebf948804fd7ea7c13 to your computer and use it in GitHub Desktop.
2 clients aquired the same InterProcessLock?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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