Zookeeper Application scenario exercise (Distributed lock)

Source: Internet
Author: User

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;pri Vate final String root = "/locks";p rivate string myznode;//represents the current node information private String waitznode;private static Logger Logger = Loggerfactory.getlogger (distributedlock.class);p rivate curatorframework client;privateCountdownlatch latch = new Countdownlatch (1);p ublic distributedlock (String connectstring, String lockname) { This.lockname = Lockname;client = Curatorframeworkfactory.builder (). CONNECTIONTIMEOUTMS (TimeOut). ConnectString ( connectstring). Retrypolicy (New Retryntimes (3, up)). 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 Blocke.printstacktrace ();}}  /** * @Title: Creating root node Root * @Description: TODO * @param * @return void * @throws */private void Createroot () {try {stat stat = Client.checkexists (). Forpath (Root), if (stat! = null) {Logger.info ("Root has already exists");} else {//Create heel node Client.cre Ate (). creatingparentsifneeded (). Forpath (root);}} CAtch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} public void Getlocks () {try {Myznode = Client.create (). Withmode (createmode.ephemeral_sequential). Forpath (Root + "/" + Lockname); Logger.info (Myznode + "has created");//Remove all sub-nodes, and then find the node smaller than their own, to listen to the 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)}} Sorts the current node collections.sort (lockobjnodes);//Determines whether the current node is 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);//Monitor the node for stat stat = client.checkexists (). Usingwatcher (Deletenodewatcher). Forpath ("/" +waitznode), if (stat! = null) {System.out.println (Thread.CurrentThread ( ). GetName () + "in the Waiting State"); Else{doAction ();}}} catch (Exception e) {logger.error (E.getmessage ());}} Delete Node Event listener Curatorwatcher Deletenodewatcher = new Curatorwatcher () {public void process (Watchedevent event) throws Excep tion {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 pm 11:36:04    * @version V1.0      */package com.test;/** * @ClassName: Testcurrentzk * @Description: TODO * @author: LUCKY * @date: February 2, 2016 PM 11:36:04 */public class Testcurrentzk {public static void main (string[] args) th  Rows Exception {Thread threads[] = 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);}}


Zookeeper scenario exercise (distributed lock)

Related Article

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.