zookeeperTutorial.html 28 KB

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