Zookeeper Application scenario exercise (Distributed lock)

Source: Internet
Author: User
Tags event listener zookeeper

In normal high concurrency programs, locks are used to lock the current thread in order to ensure the consistency of the data. In a stand-alone operation, it is good to do so, for example, you can use synchronized, lock or other read and write more to lock the current thread. But in a distributed system, it's hard to do that. This can therefore be satisfied by using the characteristics of the nodes in the zookeeper. The general idea is as follows.

1. Each client goes to zookeeper to create a temporary sequential node

2. The client determines whether the node that is currently created is the smallest

3. If so, a lock is obtained to perform the current task

4. If not, find a node smaller than yourself, then listen, if deleted, you can get the lock


The above is the approximate implementation of the idea, let us follow the code to achieve a bit.

Package com.test;
Import java.util.ArrayList;
Import java.util.Collections;
Import java.util.List;

Import Java.util.concurrent.CountDownLatch;
Import Org.apache.curator.framework.CuratorFramework;
Import Org.apache.curator.framework.CuratorFrameworkFactory;
Import Org.apache.curator.framework.api.CuratorWatcher;
Import Org.apache.curator.framework.state.ConnectionState;
Import Org.apache.curator.framework.state.ConnectionStateListener;
Import Org.apache.curator.retry.RetryNTimes;
Import Org.apache.zookeeper.CreateMode;
Import org.apache.zookeeper.WatchedEvent;
Import Org.apache.zookeeper.Watcher.Event.EventType;
Import Org.apache.zookeeper.data.Stat;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory;
	public class Distributedlock {private String lockname;
	Private final int timeOut = 3000;
	Private final String root = "/locks";
	Private string myznode;//represents the current node information private string Waitznode;
	private static Logger Logger = Loggerfactory. GetLogger (Distributedlock.class); PRivate curatorframework Client;

	Private Countdownlatch latch = new Countdownlatch (1);
		Public Distributedlock (String connectstring, String lockname) {this.lockname = Lockname; Client = Curatorframeworkfactory.builder (). CONNECTIONTIMEOUTMS (TimeOut). ConnectString (connectstring). RetryPolicy
		(New Retryntimes (3, +)). Build ();
					Connectionstatelistener listener = new Connectionstatelistener () {public void statechanged (Curatorframework client,
					ConnectionState newstate) {if (newstate = = connectionstate.connected) {logger.info ("Connection succeeded");
				Latch.countdown ();

		}
			}
		};
		Client.getconnectionstatelistenable (). AddListener (listener);
		Client.start ();
			try {latch.await ();
		Createroot ();
		} catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); }}/** * @Title: Creating root node Root * @Description: TODO * @param * @return void * @throws */private void Create Root () {try {stat stat = client.Checkexists (). Forpath (root);
			if (stat! = null) {Logger.info ("Root has already exists");

			} else {//Created with node Client.create (). creatingparentsifneeded (). Forpath (root);
		}} catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); }} public void Getlocks () {try {Myznode = Client.create (). Withmode (createmode.ephemeral_sequential). Forp
			Ath (root + "/" + lockname);
			Logger.info (Myznode + "has created");
			Remove all the child nodes, and then find the node that is smaller than yourself, and listen for settings list<string> subnodes = Client.getchildren (). Forpath (root);
			Remove all node information with lockname list<string> lockobjnodes = new arraylist<string> ();
				for (String node:subnodes) {if (Node.contains (Lockname)) {Lockobjnodes.add (node);
			}}//Sort the current node collections.sort (lockobjnodes);
			Determines if the current node is not the smallest node if (myznode.equals (root + "/" + lockobjnodes.get (0))) {doAction (); } else {//Find a node that is older than its own node to listen on String submyzone = Myznode. suBstring (Myznode.lastindexof ("/") + 1);
				Waitznode = Lockobjnodes.get (Collections.binarysearch (Lockobjnodes, Submyzone)-1);
				Listen to the node stat stat = Client.checkexists (). Usingwatcher (Deletenodewatcher). Forpath ("/" +waitznode);
				if (stat! = null) {System.out.println (Thread.CurrentThread (). GetName () + "in wait state");
				} else {doAction ();
		}}} catch (Exception e) {logger.error (E.getmessage ()); }}//delete node event listener Curatorwatcher Deletenodewatcher = new Curatorwatcher () {public void process (Watchedevent event)
			Throws Exception {if (event.gettype () = = eventtype.nodedeleted) {doAction ();

	}
		}
	};
		private void DoAction () {System.out.println (Thread.CurrentThread (). GetName () + "Start Execution");
	Client.close ();
 }
}


Let's test it here.

/**     
 * @FileName: Testcurrentzk.java   
 * @Package: Com.test   
 * @Description: TODO  
 * @author: LUCKY    
 * @ date:2016 February 2 Afternoon 11:36:04   
 * @version V1.0 * * Package
com.test;

/**
 * @ClassName: Testcurrentzk
 * @Description: TODO
 * @author: LUCKY
 * @date: February 2, 2016 11:36:04
 *
/public class Testcurrentzk {public

	static void Main (string[] args) throws Exception {
		Thread thr eads[] = new THREAD[10];
		for (int i = 0; i < Threads.length, i++) {
			threads[i] = new Thread (new Runnable () {public
				void run () {
					Clienttest clienttest = new Clienttest (
							"100.66.162.36:2181", "locknametest");
					Clienttest.getlocks ();
				}
			});

			Threads[i].start ();

		}
		Thread.Sleep (Integer.max_value);
	}
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.