Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: File Locks Next: Linearizable Counters

Distributed Locks

Using ZooKeeper v3.4.12 and Curator v4.0.1, we demonstrate below how to use ZooKeeper to rewrite the previous example:

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import java.lang.management.ManagementFactory;
public class Main {
public static void main(String args[]) throws Exception {
final RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
final CuratorFramework client = CuratorFrameworkFactory.newClient("", retryPolicy);
final InterProcessMutex lock = new InterProcessMutex(client, "/path/to/lock");
final String processID = ManagementFactory.getRuntimeMXBean().getName();
try {
System.out.println(processID + " acquired the lock");
Thread.sleep(1000); // simulates other work being done
System.out.println(processID + " is releasing the lock");
} finally {
if (lock.isAcquiredInThisProcess()) {
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content