Zookeeper Implement barrier _barrier

Source: Internet
Author: User

Zookeeper Implement barrier _barrier


According to the official website of the demo, their own understanding, add the corresponding comments, here to put the code out, such as the next,

Barrier

package com.usfot;import org.apache.zookeeper.createmode;import  org.apache.zookeeper.keeperexception;import org.apache.zookeeper.watchedevent;import  org.apache.zookeeper.watcher;import org.apache.zookeeper.zoodefs;import  org.apache.zookeeper.zookeeper;import org.apache.zookeeper.data.stat;import java.util.list;/**  *  inherits watcher to achieve synchronous processing between different tasks in the distributed environment (using the reverse push of the watcher mechanism).  *  the triggering of the event causes the thread to handle it accordingly, thus avoiding the unnecessary while (true), which causes the CPU to spin out of the loop.  */public class barrier implements watcher {    private  static final String addr =  "127.0.0.1:2181";     private  ZooKeeper zk = null;    private Integer mutex;     private int size = 0;    private String root;     public barrier (string root, int size)  {        this.root = root;         this.size = size;        try {             zk = new zookeeper (addr, 10  * 1000, this);             mutex  = new integer ( -1);             stat  s = zk.exists (Root, false);             if  (s == null)  {                 zk.create (Root, new byte[0], zoodefs.ids.open_acl_unsafe,  createmode.persistent);            }         } catch  (exception e)  {             e.printstacktrace ();        }     }    /**     *  Wake up threads waiting on a mutex when the event is triggered       *  as long as the data of the node on the ZK server changes (no matter which zk client changes the data),     *  This will receive the corresponding event to wake up the corresponding thread and make the appropriate processing      *     *  @param   Event     */    public synchronized void process ( watchedevent event)  {        synchronized  (mutex)   {            mutex.notify ();         }    }    /**      *  when creating a new Znode, first hold the mutex supervisorTo enter the synchronization code block.      *  when a Znode event occurs, the process is triggered to wake up the thread waiting on the mutex.      *  determines the number of nodes created through the while loop, and the Enter method executes when the number of nodes is greater than the set value.      *     *  @param  name      *  @return      *  @throws  exception     * /    public boolean enter (String name)  throws exception {         zk.create (root +  "/"  + name, new  byte[0], zoodefs.ids.open_acl_unsafe, createmode.ephemeral);         while  (True)  {             synchronized  (Mutex)  {                 list<string> list = zk.getchIldren (root, true);                 if  (List.size ()  < size)  {                     mutex.wait ();                 } else {                     return  true;                }             }         }    }    /**     * . For the Leave method, when Delete znode, triggers the event, which wakes up the waiting thread on the mutex, through the while loop      *  determines the number of nodes, When the node is all removed, the Leave method ends.      *  so that the entire add delete Znode thread ends      *     *   @param  name     *  @return      *  @throws  KeeperException     *  @throws  InterruptedException      */    public boolean leave (String name)  throws  Keeperexception, interruptedexception {        zk.delete ( root +  "/"  + name, 0);        while  ( true)  {            synchronized  (mutex)  {                list <string> list = zk.getchildren (root, true);                 if  (List.size ()  > 0)  {                     mutex.wait ();                 } else {                      return true;                 }            }         }    }}

Barriertest

package com.usfot;import java.util.random;public class barriertest {     /**     *  starts three threads and corresponds to three ZK clients      *      *  @param  args     *  @throws  exception      */    public static void main (String  Args[])  throws Exception {        for  (int i  = 0; i < 3; i++)  {             process p = new process ("thread-"  + i, new  Barrier ("/test_node",  3));             p.start ();         }    }}class process extends  thread {    private string name;    private barrier barrier;     public process (String name, barrier barrier)  {         this.name = name;         this.barrier = barrier;    }     @Override      public void run ()  {        try {             barrier.enter (name);             system.out.println (name +  " enter");             thread.sleep (1000 + new random (). Nextint (+));             barrier.leave (name);             system.out.println (name +  " leave");         } catch  (exception e)  {             e.printstacktrace ();         }     }}

Execute this procedure, as below,

Thread-1 enterThread-2 enterThread-0 enterThread-0 leaveThread-1 leaveThread-2 leaveprocess finished with exit code 0

Open ZK's client, as below,

[Zk:localhost:2181 (CONNECTED) 8] LS/[testrootpath, Test_node, Mynode, zookeeper, zk_test0000000005, Zk_test][zk:  localhost:2181 (CONNECTED) 9] Get/test_nodeczxid = 0x800000051ctime = Tue Mar 19:08:49 CST 2015mZxid = 0x800000051mtime  = Tue Mar 19:08:49 CST 2015pZxid = 0x800000062cversion = 12dataVersion = 0aclVersion = 0ephemeralOwner = 0x0datalength = 0numChildren = 0[zk:localhost:2181 (CONNECTED) ls/test_node[][zk:localhost:2181 (CONNECTED) 11]


===============================end===============================


Zookeeper Implement barrier _barrier

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.