zookeeperTutorial.html 28 KB

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