Skip to content

Instantly share code, notes, and snippets.

@Randgalt
Created April 26, 2015 06:08
Show Gist options
  • Save Randgalt/736a682d5b896f93ab69 to your computer and use it in GitHub Desktop.
Save Randgalt/736a682d5b896f93ab69 to your computer and use it in GitHub Desktop.
public class Test {
private static final TestingServer server;
private static final CuratorFramework client;
static
{
TestingServer localServer = null;
CuratorFramework localClient = null;
try
{
localServer = new TestingServer();
localClient = CuratorFrameworkFactory.newClient(localServer.getConnectString(), new ExponentialBackoffRetry(10, 5));
}
catch ( Exception e )
{
e.printStackTrace();
System.exit(0);
}
server = localServer;
client = localClient;
}
public static void main(String[] args) {
client.start();
int numLocks = 50000;
int numThreads = 200;
String[] keyPool = new String[numLocks];
for (int i = 1; i <= numLocks; i++) {
keyPool[i - 1] = String.valueOf(100 + i);
}
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(new Job(numLocks, keyPool));
t.setName("T" + (i + 1));
t.start();
}
}
private static class Job implements Runnable {
private int numLocks;
private String[] keyPool;
public Job(int numLocks, String[] keyPool) {
this.numLocks = numLocks;
this.keyPool = keyPool;
}
@Override
public void run() {
while (true) {
int l = 0;
int h = numLocks;
String lockKey = keyPool[(new Random().nextInt(h - l) + l)];
InterProcessMutex lock = new InterProcessMutex(client, "/"+lockKey);
boolean acquired = false;
String threadName = Thread.currentThread().getName();
try {
long start = System.currentTimeMillis();
acquired = lock.acquire(0, TimeUnit.NANOSECONDS);
if (acquired) {
long end = System.currentTimeMillis();
System.out.println("lock acquired in "+ (end - start) + " ms");
} else {
System.out.println("failed to get lock");
}
} catch (Exception e) {
System.out.println(e);
} finally {
if (acquired) {
long start = System.currentTimeMillis();
try
{
lock.release();
}
catch ( Exception e )
{
System.err.println("Couldn't release lock");
}
long end = System.currentTimeMillis();
System.out.println("lock released in "+(end - start)+" ms");
}
}
}
}
}
}
@manvscode
Copy link

@Randgalt The performance is terrible using a vanilla installation of ZooKeeper. Locks take anywhere from 80ms to 300ms to be acquired.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment