Zookeeper implements exclusive locks

Exclusive locks (Exclusive Locks, referred to as X locks), also known as write locks.

If transaction T1 adds an exclusive lock to the data object o1, then during the entire locking period, only transaction T1 is allowed to read and update o1, and no other transaction can perform any type of operation on this data object (no Then lock the object) until T1 releases the exclusive lock.

public class DistributeLock implements Watcher{
	private ZooKeeper zooKeeper;
	/** zookeeper server address */
	public static final String connectString = "192.168.50.110:2181,192.168.50.111:2181,192.168.50.112:2181";
	/** Define the session expiration time */
	public static final int sessionTimeout = 5000;
	private String path = "/lock";
	
	private CountDownLatch cl;
	private CountDownLatch cl2 = new CountDownLatch(1);
	
	Thread t;
	public DistributeLock(String host ,final String path) {
		try {
			this.zooKeeper = new ZooKeeper(host, 6000,this);
			
			try {
				cl2.await();
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
		} catch (IOException e) {
			e.printStackTrace ();
		}
		this.path = path;
	}
	
	/**
	 * lock
	 */
	public void lock() {
		try {
			zooKeeper.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
		 } catch (Exception e) {
			 try {
				cl= new CountDownLatch(1);
				cl.await(1000,TimeUnit.MICROSECONDS);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		    lock();
		}
	}
	/**
	 * release lock
	 */
	public  void unlock() {
		try {
			zooKeeper.exists(path, true);
			zooKeeper.delete(path, -1);
		} catch (InterruptedException e) {
			e.printStackTrace ();
		} catch (KeeperException e) {
			e.printStackTrace ();
		}
		
	}

	@Override
	public void process(WatchedEvent event) {
		
		System.out.println("进入 process 。。。。。event = " + event);
		
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace ();
		}
		
		if (event == null) {
			return;
		}
		
		// Connection Status
		KeeperState keeperState = event.getState();
		// event type
		EventType eventType = event.getType();
		// affected path
		String path = event.getPath();
		
		String logPrefix="";
		System.out.println(logPrefix + "Received Watcher notification");
		System.out.println(logPrefix + "Connection state:\t" + keeperState.toString());
		System.out.println(logPrefix + "Event Type:\t" + eventType.toString());

		if (KeeperState.SyncConnected == keeperState) {
			// Successfully connected to ZK server
			if (EventType.None == eventType) {
				System.out.println("Successfully connected to ZK server");
				cl2.countDown();
			}
			// delete node
			else if (EventType.NodeDeleted == eventType) {
				System.out.println("Thread: "+t.getName()+logPrefix + "node" + path + " deleted");
			}
			else ;
		}
		else if (KeeperState.Disconnected == keeperState) {
			System.out.println(logPrefix + "Disconnected from ZK server");
		}
		else if (KeeperState.AuthFailed == keeperState) {
			System.out.println(logPrefix + "Permission check failed");
		}
		else if (KeeperState.Expired == keeperState) {
			System.out.println(logPrefix + "Session invalid");
		}
		else ;

		System.out.println("--------------------------------------------");

	}
}

Test class (unlocked):

public class LockTest implements Runnable {
	static int i = 0;

	DistributeLock lock = new DistributeLock(ZookeeperUtil.connectString, "/lock");

	@Override
	public void run() {
		// lock.lock();
		for (int j = 0; j < 1000000; j++) {
			i++;
		}
		// lock.unlock();
	}

	public static void main(String[] args) throws InterruptedException {
		LockTest lockTest2 = new LockTest();
		LockTest lockTest1 = new LockTest();
		Thread thread = new Thread(lockTest2);
		Thread thread2 = new Thread(lockTest1);
		thread.start();
		thread2.start();
		thread.join();
		thread2.join();
		System.out.println(i);

	}

Test Results:

Test class (locked):

public class LockTest implements Runnable {
	static int i = 0;

	DistributeLock lock = new DistributeLock(ZookeeperUtil.connectString, "/lock");

	@Override
	public void run() {
		lock.lock();
		for (int j = 0; j < 1000000; j++) {
			i++;
		}
		lock.unlock();
	}

	public static void main(String[] args) throws InterruptedException {
		LockTest lockTest2 = new LockTest();
		LockTest lockTest1 = new LockTest();
		Thread thread = new Thread(lockTest2);
		Thread thread2 = new Thread(lockTest1);
		thread.start();
		thread2.start();
		thread.join();
		thread2.join();
		System.out.println(i);

	}

}

Test Results:


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324523578&siteId=291194637