zookeeperTutorial.html 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta content="Apache Forrest" name="Generator">
  6. <meta name="Forrest-version" content="0.8">
  7. <meta name="Forrest-skin-name" content="pelt">
  8. <title>Programming with ZooKeeper - A basic tutorial</title>
  9. <link type="text/css" href="skin/basic.css" rel="stylesheet">
  10. <link media="screen" type="text/css" href="skin/screen.css" rel="stylesheet">
  11. <link media="print" type="text/css" href="skin/print.css" rel="stylesheet">
  12. <link type="text/css" href="skin/profile.css" rel="stylesheet">
  13. <script src="skin/getBlank.js" language="javascript" type="text/javascript"></script><script src="skin/getMenu.js" language="javascript" type="text/javascript"></script><script src="skin/fontsize.js" language="javascript" type="text/javascript"></script>
  14. <link rel="shortcut icon" href="images/favicon.ico">
  15. </head>
  16. <body onload="init()">
  17. <script type="text/javascript">ndeSetTextSize();</script>
  18. <div id="top">
  19. <!--+
  20. |breadtrail
  21. +-->
  22. <div class="breadtrail">
  23. <a href="http://www.apache.org/">Apache</a> &gt; <a href="http://hadoop.apache.org/">Hadoop</a> &gt; <a href="http://hadoop.apache.org/zookeeper/">ZooKeeper</a><script src="skin/breadcrumbs.js" language="JavaScript" type="text/javascript"></script>
  24. </div>
  25. <!--+
  26. |header
  27. +-->
  28. <div class="header">
  29. <!--+
  30. |start group logo
  31. +-->
  32. <div class="grouplogo">
  33. <a href="http://hadoop.apache.org/"><img class="logoImage" alt="Hadoop" src="images/hadoop-logo.jpg" title="Apache Hadoop"></a>
  34. </div>
  35. <!--+
  36. |end group logo
  37. +-->
  38. <!--+
  39. |start Project Logo
  40. +-->
  41. <div class="projectlogo">
  42. <a href="http://hadoop.apache.org/zookeeper/"><img class="logoImage" alt="ZooKeeper" src="images/zookeeper_small.gif" title="The Hadoop database"></a>
  43. </div>
  44. <!--+
  45. |end Project Logo
  46. +-->
  47. <!--+
  48. |start Search
  49. +-->
  50. <div class="searchbox">
  51. <form action="http://www.google.com/search" method="get" class="roundtopsmall">
  52. <input value="hadoop.apache.org" name="sitesearch" type="hidden"><input onFocus="getBlank (this, 'Search the site with google');" size="25" name="q" id="query" type="text" value="Search the site with google">&nbsp;
  53. <input name="Search" value="Search" type="submit">
  54. </form>
  55. </div>
  56. <!--+
  57. |end search
  58. +-->
  59. <!--+
  60. |start Tabs
  61. +-->
  62. <ul id="tabs">
  63. <li>
  64. <a class="unselected" href="http://hadoop.apache.org/zookeeper/">Project</a>
  65. </li>
  66. <li>
  67. <a class="unselected" href="http://wiki.apache.org/hadoop/ZooKeeper">Wiki</a>
  68. </li>
  69. <li class="current">
  70. <a class="selected" href="index.html">ZooKeeper Documentation</a>
  71. </li>
  72. </ul>
  73. <!--+
  74. |end Tabs
  75. +-->
  76. </div>
  77. </div>
  78. <div id="main">
  79. <div id="publishedStrip">
  80. <!--+
  81. |start Subtabs
  82. +-->
  83. <div id="level2tabs"></div>
  84. <!--+
  85. |end Endtabs
  86. +-->
  87. <script type="text/javascript"><!--
  88. document.write("Last Published: " + document.lastModified);
  89. // --></script>
  90. </div>
  91. <!--+
  92. |breadtrail
  93. +-->
  94. <div class="breadtrail">
  95. &nbsp;
  96. </div>
  97. <!--+
  98. |start Menu, mainarea
  99. +-->
  100. <!--+
  101. |start Menu
  102. +-->
  103. <div id="menu">
  104. <div onclick="SwitchMenu('menu_1.1', 'skin/')" id="menu_1.1Title" class="menutitle">Overview</div>
  105. <div id="menu_1.1" class="menuitemgroup">
  106. <div class="menuitem">
  107. <a href="index.html">Welcome</a>
  108. </div>
  109. <div class="menuitem">
  110. <a href="zookeeperOver.html">Overview</a>
  111. </div>
  112. <div class="menuitem">
  113. <a href="zookeeperStarted.html">Getting Started</a>
  114. </div>
  115. <div class="menuitem">
  116. <a href="releasenotes.html">Release Notes</a>
  117. </div>
  118. </div>
  119. <div onclick="SwitchMenu('menu_selected_1.2', 'skin/')" id="menu_selected_1.2Title" class="menutitle" style="background-image: url('skin/images/chapter_open.gif');">Developer</div>
  120. <div id="menu_selected_1.2" class="selectedmenuitemgroup" style="display: block;">
  121. <div class="menuitem">
  122. <a href="api/index.html">API Docs</a>
  123. </div>
  124. <div class="menuitem">
  125. <a href="zookeeperProgrammers.html">Programmer's Guide</a>
  126. </div>
  127. <div class="menuitem">
  128. <a href="javaExample.html">Java Example</a>
  129. </div>
  130. <div class="menupage">
  131. <div class="menupagetitle">Barrier and Queue Tutorial</div>
  132. </div>
  133. <div class="menuitem">
  134. <a href="recipes.html">Recipes</a>
  135. </div>
  136. </div>
  137. <div onclick="SwitchMenu('menu_1.3', 'skin/')" id="menu_1.3Title" class="menutitle">Admin &amp; Ops</div>
  138. <div id="menu_1.3" class="menuitemgroup">
  139. <div class="menuitem">
  140. <a href="zookeeperAdmin.html">Administrator's Guide</a>
  141. </div>
  142. </div>
  143. <div onclick="SwitchMenu('menu_1.4', 'skin/')" id="menu_1.4Title" class="menutitle">Contributor</div>
  144. <div id="menu_1.4" class="menuitemgroup">
  145. <div class="menuitem">
  146. <a href="zookeeperInternals.html">ZooKeeper Internals</a>
  147. </div>
  148. </div>
  149. <div onclick="SwitchMenu('menu_1.5', 'skin/')" id="menu_1.5Title" class="menutitle">Informal Documentation</div>
  150. <div id="menu_1.5" class="menuitemgroup">
  151. <div class="menuitem">
  152. <a href="http://wiki.apache.org/hadoop/ZooKeeper">Wiki</a>
  153. </div>
  154. <div class="menuitem">
  155. <a href="http://wiki.apache.org/hadoop/ZooKeeper/FAQ">FAQ</a>
  156. </div>
  157. <div class="menuitem">
  158. <a href="http://hadoop.apache.org/zookeeper/mailing_lists.html">Mailing Lists</a>
  159. </div>
  160. <div class="menuitem">
  161. <a href="zookeeperOtherInfo.html">Other Info</a>
  162. </div>
  163. </div>
  164. <div id="credit"></div>
  165. <div id="roundbottom">
  166. <img style="display: none" class="corner" height="15" width="15" alt="" src="skin/images/rc-b-l-15-1body-2menu-3menu.png"></div>
  167. <!--+
  168. |alternative credits
  169. +-->
  170. <div id="credit2"></div>
  171. </div>
  172. <!--+
  173. |end Menu
  174. +-->
  175. <!--+
  176. |start content
  177. +-->
  178. <div id="content">
  179. <div title="Portable Document Format" class="pdflink">
  180. <a class="dida" href="zookeeperTutorial.pdf"><img alt="PDF -icon" src="skin/images/pdfdoc.gif" class="skin"><br>
  181. PDF</a>
  182. </div>
  183. <h1>Programming with ZooKeeper - A basic tutorial</h1>
  184. <div id="minitoc-area">
  185. <ul class="minitoc">
  186. <li>
  187. <a href="#ch_Introduction">Introduction</a>
  188. </li>
  189. <li>
  190. <a href="#sc_barriers">Barriers</a>
  191. </li>
  192. <li>
  193. <a href="#sc_producerConsumerQueues">Producer-Consumer Queues</a>
  194. </li>
  195. <li>
  196. <a href="#sc_sourceListing">Complete Source Listing</a>
  197. </li>
  198. </ul>
  199. </div>
  200. <a name="N10009"></a><a name="ch_Introduction"></a>
  201. <h2 class="h3">Introduction</h2>
  202. <div class="section">
  203. <p>In this tutorial, we show simple implementations of barriers and
  204. producer-consumer queues using ZooKeeper. We call the respective classes Barrier and Queue.
  205. These examples assume that you have at least one ZooKeeper server running.</p>
  206. <p>Both primitives use the following common excerpt of code:</p>
  207. <pre class="code">
  208. static ZooKeeper zk = null;
  209. static Integer mutex;
  210. String root;
  211. SyncPrimitive(String address) {
  212. if(zk == null){
  213. try {
  214. System.out.println("Starting ZK:");
  215. zk = new ZooKeeper(address, 3000, this);
  216. mutex = new Integer(-1);
  217. System.out.println("Finished starting ZK: " + zk);
  218. } catch (IOException e) {
  219. System.out.println(e.toString());
  220. zk = null;
  221. }
  222. }
  223. //else mutex = new Integer(-1);
  224. }
  225. synchronized public void process(WatchedEvent event) {
  226. synchronized (mutex) {
  227. //System.out.println("Process: " + event.getType());
  228. mutex.notify();
  229. }
  230. }
  231. </pre>
  232. <p>Both classes extend SyncPrimitive. In this way, we execute steps that are
  233. common to all primitives in the constructor of SyncPrimitive. To keep the examples
  234. simple, we create a ZooKeeper object the first time we instantiate either a barrier
  235. object or a queue object, and we declare a static variable that is a reference
  236. to this object. The subsequent instances of Barrier and Queue check whether a
  237. ZooKeeper object exists. Alternatively, we could have the application creating a
  238. ZooKeeper object and passing it to the constructor of Barrier and Queue.</p>
  239. <p>
  240. We use the process() method to process notifications triggered due to watches.
  241. In the following discussion, we present code that sets watches. A watch is internal
  242. structure that enables ZooKeeper to notify a client of a change to a node. For example,
  243. if a client is waiting for other clients to leave a barrier, then it can set a watch and
  244. wait for modifications to a particular node, which can indicate that it is the end of the wait.
  245. This point becomes clear once we go over the examples.
  246. </p>
  247. </div>
  248. <a name="N1001F"></a><a name="sc_barriers"></a>
  249. <h2 class="h3">Barriers</h2>
  250. <div class="section">
  251. <p>
  252. A barrier is a primitive that enables a group of processes to synchronize the
  253. beginning and the end of a computation. The general idea of this implementation
  254. is to have a barrier node that serves the purpose of being a parent for individual
  255. process nodes. Suppose that we call the barrier node "/b1". Each process "p" then
  256. creates a node "/b1/p". Once enough processes have created their corresponding
  257. nodes, joined processes can start the computation.
  258. </p>
  259. <p>In this example, each process instantiates a Barrier object, and its constructor takes as parameters:</p>
  260. <ul>
  261. <li>
  262. <p>the address of a ZooKeeper server (e.g., "zoo1.foo.com:2181")</p>
  263. </li>
  264. <li>
  265. <p>the path of the barrier node on ZooKeeper (e.g., "/b1")</p>
  266. </li>
  267. <li>
  268. <p>the size of the group of processes</p>
  269. </li>
  270. </ul>
  271. <p>The constructor of Barrier passes the address of the Zookeeper server to the
  272. constructor of the parent class. The parent class creates a ZooKeeper instance if
  273. one does not exist. The constructor of Barrier then creates a
  274. barrier node on ZooKeeper, which is the parent node of all process nodes, and
  275. we call root (<strong>Note:</strong> This is not the ZooKeeper root "/").</p>
  276. <pre class="code">
  277. /**
  278. * Barrier constructor
  279. *
  280. * @param address
  281. * @param name
  282. * @param size
  283. */
  284. Barrier(String address, String name, int size) {
  285. super(address);
  286. this.root = name;
  287. this.size = size;
  288. // Create barrier node
  289. if (zk != null) {
  290. try {
  291. Stat s = zk.exists(root, false);
  292. if (s == null) {
  293. zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE,
  294. CreateMode.PERSISTENT);
  295. }
  296. } catch (KeeperException e) {
  297. System.out
  298. .println("Keeper exception when instantiating queue: "
  299. + e.toString());
  300. } catch (InterruptedException e) {
  301. System.out.println("Interrupted exception");
  302. }
  303. }
  304. // My node name
  305. try {
  306. name = new String(InetAddress.getLocalHost().getCanonicalHostName().toString());
  307. } catch (UnknownHostException e) {
  308. System.out.println(e.toString());
  309. }
  310. }
  311. </pre>
  312. <p>
  313. To enter the barrier, a process calls enter(). The process creates a node under
  314. the root to represent it, using its host name to form the node name. It then wait
  315. until enough processes have entered the barrier. A process does it by checking
  316. the number of children the root node has with "getChildren()", and waiting for
  317. notifications in the case it does not have enough. To receive a notification when
  318. there is a change to the root node, a process has to set a watch, and does it
  319. through the call to "getChildren()". In the code, we have that "getChildren()"
  320. has two parameters. The first one states the node to read from, and the second is
  321. a boolean flag that enables the process to set a watch. In the code the flag is true.
  322. </p>
  323. <pre class="code">
  324. /**
  325. * Join barrier
  326. *
  327. * @return
  328. * @throws KeeperException
  329. * @throws InterruptedException
  330. */
  331. boolean enter() throws KeeperException, InterruptedException{
  332. zk.create(root + "/" + name, new byte[0], Ids.OPEN_ACL_UNSAFE,
  333. CreateMode.EPHEMERAL);
  334. while (true) {
  335. synchronized (mutex) {
  336. List&lt;String&gt; list = zk.getChildren(root, true);
  337. if (list.size() &lt; size) {
  338. mutex.wait();
  339. } else {
  340. return true;
  341. }
  342. }
  343. }
  344. }
  345. </pre>
  346. <p>
  347. Note that enter() throws both KeeperException and InterruptedException, so it is
  348. the reponsability of the application to catch and handle such exceptions.</p>
  349. <p>
  350. Once the computation is finished, a process calls leave() to leave the barrier.
  351. First it deletes its corresponding node, and then it gets the children of the root
  352. node. If there is at least one child, then it waits for a notification (obs: note
  353. that the second parameter of the call to getChildren() is true, meaning that
  354. ZooKeeper has to set a watch on the the root node). Upon reception of a notification,
  355. it checks once more whether the root node has any child.</p>
  356. <pre class="code">
  357. /**
  358. * Wait until all reach barrier
  359. *
  360. * @return
  361. * @throws KeeperException
  362. * @throws InterruptedException
  363. */
  364. boolean leave() throws KeeperException, InterruptedException{
  365. zk.delete(root + "/" + name, 0);
  366. while (true) {
  367. synchronized (mutex) {
  368. List&lt;String&gt; list = zk.getChildren(root, true);
  369. if (list.size() &gt; 0) {
  370. mutex.wait();
  371. } else {
  372. return true;
  373. }
  374. }
  375. }
  376. }
  377. }
  378. </pre>
  379. </div>
  380. <a name="N10051"></a><a name="sc_producerConsumerQueues"></a>
  381. <h2 class="h3">Producer-Consumer Queues</h2>
  382. <div class="section">
  383. <p>
  384. A producer-consumer queue is a distributed data estructure thata group of processes
  385. use to generate and consume items. Producer processes create new elements and add
  386. them to the queue. Consumer processes remove elements from the list, and process them.
  387. In this implementation, the elements are simple integers. The queue is represented
  388. by a root node, and to add an element to the queue, a producer process creates a new node,
  389. a child of the root node.
  390. </p>
  391. <p>
  392. The following excerpt of code corresponds to the constructor of the object. As
  393. with Barrier objects, it first calls the constructor of the parent class, SyncPrimitive,
  394. that creates a ZooKeeper object if one doesn't exist. It then verifies if the root
  395. node of the queue exists, and creates if it doesn't.
  396. </p>
  397. <pre class="code">
  398. /**
  399. * Constructor of producer-consumer queue
  400. *
  401. * @param address
  402. * @param name
  403. */
  404. Queue(String address, String name) {
  405. super(address);
  406. this.root = name;
  407. // Create ZK node name
  408. if (zk != null) {
  409. try {
  410. Stat s = zk.exists(root, false);
  411. if (s == null) {
  412. zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE,
  413. CreateMode.PERSISTENT);
  414. }
  415. } catch (KeeperException e) {
  416. System.out
  417. .println("Keeper exception when instantiating queue: "
  418. + e.toString());
  419. } catch (InterruptedException e) {
  420. System.out.println("Interrupted exception");
  421. }
  422. }
  423. }
  424. </pre>
  425. <p>
  426. A producer process calls "produce()" to add an element to the queue, and passes
  427. an integer as an argument. To add an element to the queue, the method creates a
  428. new node using "create()", and uses the SEQUENCE flag to instruct ZooKeeper to
  429. append the value of the sequencer counter associated to the root node. In this way,
  430. we impose a total order on the elements of the queue, thus guaranteeing that the
  431. oldest element of the queue is the next one consumed.
  432. </p>
  433. <pre class="code">
  434. /**
  435. * Add element to the queue.
  436. *
  437. * @param i
  438. * @return
  439. */
  440. boolean produce(int i) throws KeeperException, InterruptedException{
  441. ByteBuffer b = ByteBuffer.allocate(4);
  442. byte[] value;
  443. // Add child with value i
  444. b.putInt(i);
  445. value = b.array();
  446. zk.create(root + "/element", value, Ids.OPEN_ACL_UNSAFE,
  447. CreateMode.PERSISTENT_SEQUENTIAL);
  448. return true;
  449. }
  450. </pre>
  451. <p>
  452. To consume an element, a consumer process obtains the children of the root node,
  453. reads the node with smallest counter value, and returns the element. Note that
  454. if there is a conflict, then one of the two contending processes won't be able to
  455. delete the node and the delete operation will throw an exception.</p>
  456. <p>
  457. A call to getChildren() returns the list of children in lexicographic order.
  458. As lexicographic order does not necessary follow the numerical order of the counter
  459. values, we need to decide which element is the smallest. To decide which one has
  460. the smallest counter value, we traverse the list, and remove the prefix "element"
  461. from each one.</p>
  462. <pre class="code">
  463. /**
  464. * Remove first element from the queue.
  465. *
  466. * @return
  467. * @throws KeeperException
  468. * @throws InterruptedException
  469. */
  470. int consume() throws KeeperException, InterruptedException{
  471. int retvalue = -1;
  472. Stat stat = null;
  473. // Get the first element available
  474. while (true) {
  475. synchronized (mutex) {
  476. List&lt;String&gt; list = zk.getChildren(root, true);
  477. if (list.size() == 0) {
  478. System.out.println("Going to wait");
  479. mutex.wait();
  480. } else {
  481. Integer min = new Integer(list.get(0).substring(7));
  482. for(String s : list){
  483. Integer tempValue = new Integer(s.substring(7));
  484. //System.out.println("Temporary value: " + tempValue);
  485. if(tempValue &lt; min) min = tempValue;
  486. }
  487. System.out.println("Temporary value: " + root + "/element" + min);
  488. byte[] b = zk.getData(root + "/element" + min,
  489. false, stat);
  490. zk.delete(root + "/element" + min, 0);
  491. ByteBuffer buffer = ByteBuffer.wrap(b);
  492. retvalue = buffer.getInt();
  493. return retvalue;
  494. }
  495. }
  496. }
  497. }
  498. }
  499. </pre>
  500. </div>
  501. <a name="N1006F"></a><a name="sc_sourceListing"></a>
  502. <h2 class="h3">Complete Source Listing</h2>
  503. <div class="section">
  504. <div class="note example">
  505. <div class="label">SyncPrimitive.Java</div>
  506. <div class="content">
  507. <title>SyncPrimitive.Java</title>
  508. <pre class="code">
  509. import java.io.IOException;
  510. import java.net.InetAddress;
  511. import java.net.UnknownHostException;
  512. import java.nio.ByteBuffer;
  513. import java.util.List;
  514. import java.util.Random;
  515. import org.apache.zookeeper.CreateMode;
  516. import org.apache.zookeeper.KeeperException;
  517. import org.apache.zookeeper.WatchedEvent;
  518. import org.apache.zookeeper.Watcher;
  519. import org.apache.zookeeper.ZooKeeper;
  520. import org.apache.zookeeper.ZooDefs.Ids;
  521. import org.apache.zookeeper.data.Stat;
  522. public class SyncPrimitive implements Watcher {
  523. static ZooKeeper zk = null;
  524. static Integer mutex;
  525. String root;
  526. SyncPrimitive(String address) {
  527. if(zk == null){
  528. try {
  529. System.out.println("Starting ZK:");
  530. zk = new ZooKeeper(address, 3000, this);
  531. mutex = new Integer(-1);
  532. System.out.println("Finished starting ZK: " + zk);
  533. } catch (IOException e) {
  534. System.out.println(e.toString());
  535. zk = null;
  536. }
  537. }
  538. //else mutex = new Integer(-1);
  539. }
  540. synchronized public void process(WatchedEvent event) {
  541. synchronized (mutex) {
  542. //System.out.println("Process: " + event.getType());
  543. mutex.notify();
  544. }
  545. }
  546. /**
  547. * Barrier
  548. */
  549. static public class Barrier extends SyncPrimitive {
  550. int size;
  551. String name;
  552. /**
  553. * Barrier constructor
  554. *
  555. * @param address
  556. * @param name
  557. * @param size
  558. */
  559. Barrier(String address, String name, int size) {
  560. super(address);
  561. this.root = name;
  562. this.size = size;
  563. // Create barrier node
  564. if (zk != null) {
  565. try {
  566. Stat s = zk.exists(root, false);
  567. if (s == null) {
  568. zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE,
  569. CreateMode.PERSISTENT);
  570. }
  571. } catch (KeeperException e) {
  572. System.out
  573. .println("Keeper exception when instantiating queue: "
  574. + e.toString());
  575. } catch (InterruptedException e) {
  576. System.out.println("Interrupted exception");
  577. }
  578. }
  579. // My node name
  580. try {
  581. name = new String(InetAddress.getLocalHost().getCanonicalHostName().toString());
  582. } catch (UnknownHostException e) {
  583. System.out.println(e.toString());
  584. }
  585. }
  586. /**
  587. * Join barrier
  588. *
  589. * @return
  590. * @throws KeeperException
  591. * @throws InterruptedException
  592. */
  593. boolean enter() throws KeeperException, InterruptedException{
  594. zk.create(root + "/" + name, new byte[0], Ids.OPEN_ACL_UNSAFE,
  595. CreateMode.EPHEMERAL);
  596. while (true) {
  597. synchronized (mutex) {
  598. List&lt;String&gt; list = zk.getChildren(root, true);
  599. if (list.size() &lt; size) {
  600. mutex.wait();
  601. } else {
  602. return true;
  603. }
  604. }
  605. }
  606. }
  607. /**
  608. * Wait until all reach barrier
  609. *
  610. * @return
  611. * @throws KeeperException
  612. * @throws InterruptedException
  613. */
  614. boolean leave() throws KeeperException, InterruptedException{
  615. zk.delete(root + "/" + name, 0);
  616. while (true) {
  617. synchronized (mutex) {
  618. List&lt;String&gt; list = zk.getChildren(root, true);
  619. if (list.size() &gt; 0) {
  620. mutex.wait();
  621. } else {
  622. return true;
  623. }
  624. }
  625. }
  626. }
  627. }
  628. /**
  629. * Producer-Consumer queue
  630. */
  631. static public class Queue extends SyncPrimitive {
  632. /**
  633. * Constructor of producer-consumer queue
  634. *
  635. * @param address
  636. * @param name
  637. */
  638. Queue(String address, String name) {
  639. super(address);
  640. this.root = name;
  641. // Create ZK node name
  642. if (zk != null) {
  643. try {
  644. Stat s = zk.exists(root, false);
  645. if (s == null) {
  646. zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE,
  647. CreateMode.PERSISTENT);
  648. }
  649. } catch (KeeperException e) {
  650. System.out
  651. .println("Keeper exception when instantiating queue: "
  652. + e.toString());
  653. } catch (InterruptedException e) {
  654. System.out.println("Interrupted exception");
  655. }
  656. }
  657. }
  658. /**
  659. * Add element to the queue.
  660. *
  661. * @param i
  662. * @return
  663. */
  664. boolean produce(int i) throws KeeperException, InterruptedException{
  665. ByteBuffer b = ByteBuffer.allocate(4);
  666. byte[] value;
  667. // Add child with value i
  668. b.putInt(i);
  669. value = b.array();
  670. zk.create(root + "/element", value, Ids.OPEN_ACL_UNSAFE,
  671. CreateMode.PERSISTENT_SEQUENTIAL);
  672. return true;
  673. }
  674. /**
  675. * Remove first element from the queue.
  676. *
  677. * @return
  678. * @throws KeeperException
  679. * @throws InterruptedException
  680. */
  681. int consume() throws KeeperException, InterruptedException{
  682. int retvalue = -1;
  683. Stat stat = null;
  684. // Get the first element available
  685. while (true) {
  686. synchronized (mutex) {
  687. List&lt;String&gt; list = zk.getChildren(root, true);
  688. if (list.size() == 0) {
  689. System.out.println("Going to wait");
  690. mutex.wait();
  691. } else {
  692. Integer min = new Integer(list.get(0).substring(7));
  693. for(String s : list){
  694. Integer tempValue = new Integer(s.substring(7));
  695. //System.out.println("Temporary value: " + tempValue);
  696. if(tempValue &lt; min) min = tempValue;
  697. }
  698. System.out.println("Temporary value: " + root + "/element" + min);
  699. byte[] b = zk.getData(root + "/element" + min,
  700. false, stat);
  701. zk.delete(root + "/element" + min, 0);
  702. ByteBuffer buffer = ByteBuffer.wrap(b);
  703. retvalue = buffer.getInt();
  704. return retvalue;
  705. }
  706. }
  707. }
  708. }
  709. }
  710. public static void main(String args[]) {
  711. if (args[0].equals("qTest"))
  712. queueTest(args);
  713. else
  714. barrierTest(args);
  715. }
  716. public static void queueTest(String args[]) {
  717. Queue q = new Queue(args[1], "/app1");
  718. System.out.println("Input: " + args[1]);
  719. int i;
  720. Integer max = new Integer(args[2]);
  721. if (args[3].equals("p")) {
  722. System.out.println("Producer");
  723. for (i = 0; i &lt; max; i++)
  724. try{
  725. q.produce(10 + i);
  726. } catch (KeeperException e){
  727. } catch (InterruptedException e){
  728. }
  729. } else {
  730. System.out.println("Consumer");
  731. for (i = 0; i &lt; max; i++) {
  732. try{
  733. int r = q.consume();
  734. System.out.println("Item: " + r);
  735. } catch (KeeperException e){
  736. i--;
  737. } catch (InterruptedException e){
  738. }
  739. }
  740. }
  741. }
  742. public static void barrierTest(String args[]) {
  743. Barrier b = new Barrier(args[1], "/b1", new Integer(args[2]));
  744. try{
  745. boolean flag = b.enter();
  746. System.out.println("Entered barrier: " + args[2]);
  747. if(!flag) System.out.println("Error when entering the barrier");
  748. } catch (KeeperException e){
  749. } catch (InterruptedException e){
  750. }
  751. // Generate random integer
  752. Random rand = new Random();
  753. int r = rand.nextInt(100);
  754. // Loop for rand iterations
  755. for (int i = 0; i &lt; r; i++) {
  756. try {
  757. Thread.sleep(100);
  758. } catch (InterruptedException e) {
  759. }
  760. }
  761. try{
  762. b.leave();
  763. } catch (KeeperException e){
  764. } catch (InterruptedException e){
  765. }
  766. System.out.println("Left barrier");
  767. }
  768. }
  769. </pre>
  770. </div>
  771. </div>
  772. </div>
  773. <p align="right">
  774. <font size="-2"></font>
  775. </p>
  776. </div>
  777. <!--+
  778. |end content
  779. +-->
  780. <div class="clearboth">&nbsp;</div>
  781. </div>
  782. <div id="footer">
  783. <!--+
  784. |start bottomstrip
  785. +-->
  786. <div class="lastmodified">
  787. <script type="text/javascript"><!--
  788. document.write("Last Published: " + document.lastModified);
  789. // --></script>
  790. </div>
  791. <div class="copyright">
  792. Copyright &copy;
  793. 2008 <a href="http://www.apache.org/licenses/">The Apache Software Foundation.</a>
  794. </div>
  795. <!--+
  796. |end bottomstrip
  797. +-->
  798. </div>
  799. </body>
  800. </html>