{"id":392,"date":"2018-05-28T11:46:16","date_gmt":"2018-05-27T23:46:16","guid":{"rendered":"https:\/\/content.ronella.xyz\/apps\/wordpress\/?p=392"},"modified":"2018-06-01T14:58:58","modified_gmt":"2018-06-01T02:58:58","slug":"using-cyclicbarrier-with-java","status":"publish","type":"post","link":"https:\/\/www.ronella.xyz\/?p=392","title":{"rendered":"Using CyclicBarrier with Java"},"content":{"rendered":"<p>CyclicBarrier was designed to allow threads to wait for each other to a certain barrier and doing it again and again <em>(i.e. the reason why it is called cyclic)<\/em>.<\/p>\n<h5><strong>Creating a CyclicBarrier aware Task<\/strong><\/h5>\n<ol>\n<li><strong>Create a task<\/strong> that will <strong>accepts and instance of CyclicBarrier<\/strong> like the following snippet <em>(i.e. <a href=\"#complete_code\">the complete code<\/a> will be at the bottom).<\/em>\n<pre>public Teller(<strong>CyclicBarrier barrier<\/strong>, String message) {\r\n    <strong>_barrier = barrier<\/strong>;\r\n    _message = message;\r\n}<\/pre>\n<\/li>\n<li>Within the task we must call the <strong>await<\/strong> method of the instance of the CyclicBarrier like the following snippet <em>(i.e. <a href=\"#complete_code\">the complete code<\/a> will be at the bottom).<\/em> The number of call to this method is the one being tracked by the instance of the CyclicBarrier to compare to the number of parties <em>(i.e. normally the first or only argument of the constructor.)<\/em>\u00a0specified during it's initialization.\n<pre>@Override\r\npublic String call() throws Exception {\r\n    System.out.println(\"Processing: \" + _message);\r\n    _barrier.<strong>await()<\/strong>;\r\n    return _message;\r\n}<\/pre>\n<\/li>\n<\/ol>\n<h5>Using the CyclicBarrier aware Task<\/h5>\n<ol>\n<li><strong>Create an instance of CyclicBarrier<\/strong> class with the <strong>expected number of parties<\/strong>\u00a0<em>(i.e. normally this is the first or only argument of the constructor)<\/em> before it unblocks itself for all the threads waiting then back to blocking. Optionally, we can also pass a <strong>second argument of type Runnable<\/strong> that will only be invoked when the barrier unblocks like the following snippet <em>(i.e. <a href=\"#complete_code\">the complete code<\/a> will be at the bottom)<\/em>.\n<pre>CyclicBarrier barrier = new CyclicBarrier(<strong>2 \/*The number of parties. *\/<\/strong>\r\n, <strong>() -&gt; System.out.println(\"Barrier open.\") \/*The logic to call when the barrier unblocks. *\/<\/strong>\r\n);<\/pre>\n<\/li>\n<li>Submit <strong>a number of tasks that corresponds to the multiple of the number of parties<\/strong> <em>(e.g.\u00a0from step 1 it could be multiple of 2) <\/em>from step 1 like the following snippet <em>(i.e. <a href=\"#complete_code\">the complete code<\/a> will be at the bottom)<\/em>:\n<pre>futures.add(<strong>executor.submit(new Teller(barrier, \"One\"))<\/strong>);\r\nfutures.add(<strong>executor.submit(new Teller(barrier, \"Two\"))<\/strong>);\r\nfutures.add(<strong>executor.submit(new Teller(barrier, \"Three\"))<\/strong>);\r\nfutures.add(<strong>executor.submit(new Teller(barrier, \"Four\"))<\/strong>);\r\n\r\nfutures.forEach((Future future) -&gt; {\r\n    try {\r\n        System.out.println(<strong>future.get()<\/strong>);\r\n    } catch (InterruptedException | ExecutionException e) {\r\n        e.printStackTrace();\r\n    }\r\n});<\/pre>\n<\/li>\n<\/ol>\n<h5>Observation<\/h5>\n<p>Upon running <a href=\"#complete_code\">the complete code<\/a>:<\/p>\n<ul>\n<li>We must notice that the following message will be executed every multiple of 2 <em>(i.e. observe the processing message)<\/em>:\n<pre>Barrier open.<\/pre>\n<\/li>\n<li>The following message <em>(i.e. can be in any order)<\/em> will never be displayed before One and Two <em>(i.e. can be in any order)<\/em>:\n<pre>Three\r\nFour<\/pre>\n<\/li>\n<\/ul>\n<h5 id=\"complete_code\"><strong>The Complete Code<\/strong><\/h5>\n<pre>package xyz.ronella.concurrency;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\nimport java.util.concurrent.*;\r\n\r\npublic class Barrier {\r\n\r\n    public static void main(String[] args) {\r\n\r\n        class Teller implements Callable {\r\n\r\n            private CyclicBarrier _barrier;\r\n            private String _message;\r\n\r\n            public Teller(CyclicBarrier barrier, String message) {\r\n                _barrier = barrier;\r\n                _message = message;\r\n            }\r\n\r\n            @Override\r\n            public String call() throws Exception {\r\n                System.out.println(\"Processing: \" + _message);\r\n                _barrier.await();\r\n                return _message;\r\n            }\r\n        }\r\n\r\n        ExecutorService executor = Executors.newFixedThreadPool(2);\r\n\r\n        CyclicBarrier barrier = new CyclicBarrier(2 \/*The number of parties. *\/\r\n                , () -&gt; System.out.println(\"Barrier open.\") \/*The logic to call when the barrier unblocks. *\/\r\n        );\r\n\r\n        List&lt;Future&gt; futures = new ArrayList&lt;&gt;();\r\n\r\n        try {\r\n            futures.add(executor.submit(new Teller(barrier, \"One\")));\r\n            futures.add(executor.submit(new Teller(barrier, \"Two\")));\r\n            futures.add(executor.submit(new Teller(barrier, \"Three\")));\r\n            futures.add(executor.submit(new Teller(barrier, \"Four\")));\r\n\r\n            futures.forEach((Future future) -&gt; {\r\n                try {\r\n                    System.out.println(future.get());\r\n                } catch (InterruptedException | ExecutionException e) {\r\n                    e.printStackTrace();\r\n                }\r\n            });\r\n        }\r\n        finally {\r\n            executor.shutdown();\r\n        }\r\n    }\r\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>CyclicBarrier was designed to allow threads to wait for each other to a certain barrier and doing it again and again (i.e. the reason why it is called cyclic). Creating a CyclicBarrier aware Task Create a task that will accepts and instance of CyclicBarrier like the following snippet (i.e. the complete code will be at [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[35,33],"tags":[],"_links":{"self":[{"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/posts\/392"}],"collection":[{"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=392"}],"version-history":[{"count":20,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/posts\/392\/revisions"}],"predecessor-version":[{"id":417,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/posts\/392\/revisions\/417"}],"wp:attachment":[{"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=392"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=392"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=392"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}