zookeeperTutorial.html 29 KB

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