zookeeperTutorial.html 26 KB

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