{"id":2621,"date":"2017-05-17T21:45:24","date_gmt":"2017-05-17T16:15:24","guid":{"rendered":"http:\/\/www.java2blog.com\/?p=2621"},"modified":"2021-01-26T23:50:02","modified_gmt":"2021-01-26T18:20:02","slug":"java-cyclicbarrier-example","status":"publish","type":"post","link":"https:\/\/java2blog.com\/java-cyclicbarrier-example\/","title":{"rendered":"Java CyclicBarrier Example"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Difference_between_CountDownLatch_and_CyclicBarrier\">Difference between CountDownLatch and CyclicBarrier<\/a><\/li><li><a href=\"#Java_CyclicBarrier_example\">Java CyclicBarrier example:<\/a><\/li><\/ul><\/div>\n<p>In this post, we will see about CyclicBarrier in java. CyclicBarrier was introduced in Java 5 with other concurrency utils such as <a href=\"http:\/\/www.java2blog.com\/2015\/08\/countdownlatch-in-java.html\">CountDownLatch<\/a>, <a href=\"http:\/\/www.java2blog.com\/2014\/11\/concurrenthashmap-in-java.html\">ConcurrentHashMap<\/a> and <a href=\"http:\/\/www.java2blog.com\/2015\/12\/blockingqueue-in-java.html\">BlockingQueue<\/a>.<\/p>\n<p>CyclicBarrier is synchronized aid which allows set of threads to wait for each other at common barrier points.It is called cyclic because it can be reused once waiting threads are released.<\/p>\n<p>For example:<br \/>\nLet&#8217;s say you have 3 threads, you want all threads(terms as parties) to reach a common point and then only they should proceed ahead.In this case, you can use CyclicBarrier with 3 parties and once 3 threads reach a common point, you can call an event which will implement runnable interface and Three threads will be released.<\/p>\n<h2><span id=\"Difference_between_CountDownLatch_and_CyclicBarrier\">Difference between CountDownLatch and CyclicBarrier<\/span><\/h2>\n<p>The major difference between CyclicBarrier and CoundDownLatch is that CyclicBarrier can be reused.You can not use CountDownLatch once used. You can read more <a href=\"http:\/\/www.java2blog.com\/2016\/07\/difference-between-countdownlatch-and-cyclicbarrier-in-java.html\">differences between CountDownLatch and CyclicBarrier.<\/a><\/p>\n<h2><span id=\"Java_CyclicBarrier_example\">Java CyclicBarrier example:<\/span><\/h2>\n<p><b>Step 1: <\/b>Create a file named &quot;RunnableTask.java&quot; in package .src.org.arpit.java2blog<\/p>\n<pre name=\"code\">package org.arpit.java2blog;\n\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\n\npublic class RunnableTask implements Runnable{\n\n    CyclicBarrier cyclicBarrier;\n    long sleepTime;\n\n    RunnableTask(CyclicBarrier cyclicBarrier,long sleepTime){\n        this.cyclicBarrier=cyclicBarrier;\n        this.sleepTime=sleepTime;\n    }\n\n    @Override\n    public void run() {\n\n        try {\n            Thread.sleep(sleepTime);\n            System.out.println(Thread.currentThread().getName() +\n                    \" is waiting for \"+(cyclicBarrier.getParties()-cyclicBarrier.getNumberWaiting()-1)+ \n                    \" other threads to reach common barrier point\");\n            \/*\n             * when  3 parties will call await() method (i.e. common barrier point)\n             * CyclicBarrrierEvent will be triggered and all waiting threads will be released.\n             *\/\n            cyclicBarrier.await();\n        } catch (InterruptedException e) {\n            e.printStackTrace();\n        } catch (BrokenBarrierException e) {\n            e.printStackTrace();\n        }          \n\n        System.out.println(\"As \"+cyclicBarrier.getParties()+ \" threads have reached common barrier point \"\n                + Thread.currentThread().getName() +\n                \" has been released\");\n    }\n\n}\n<\/pre>\n<p>This is a Runnable task which will be executed by each thread.<br \/>\n<b>Step 2: <\/b>Create a file named &quot;CyclicBarrierFinishEvent.java&quot; in package .src.org.arpit.java2blog<\/p>\n<pre name=\"code\">package org.arpit.java2blog;\n\npublic class CyclicBarrierFinishEvent implements Runnable{\n\n    public void run() {\n\n           System.out.println(\"As 3 threads have reached common barrier point \"\n                        + \", CyclicBarrrierFinishEvent has been triggered\");\n           System.out.println(\"You can update shared variables if any\");\n    }\n\n}\n<\/pre>\n<p>CyclicBarrierFinishEvent will be called when 3 parties (Initialized with CyclicBarrier object) reaches to a common barrier point.<br \/>\n<b>Step 3: <\/b>Create a file named &quot;CyclicBarrierMain.java&quot; in package .src.org.arpit.java2blog<\/p>\n<pre name=\"code\">package org.arpit.java2blog;\n\nimport java.util.concurrent.CyclicBarrier;\n\n\/** @author Arpit Mandliya*\/\npublic class CyclicBarrierMain {\n    public static void main(String[] args) {\n        \/*\n         * Create CountDownLatch with 3 parties, when all 3 parties\n         * will reach common barrier point CyclicBarrrierFinishEvent will be\n         * triggered \n         *\/\n        CyclicBarrier cyclicBarrier=new CyclicBarrier(3 ,new CyclicBarrierFinishEvent());\n\n        RunnableTask runnableTask1=new RunnableTask(cyclicBarrier,1000);\n        RunnableTask runnableTask2=new RunnableTask(cyclicBarrier,2000);\n        RunnableTask runnableTask3=new RunnableTask(cyclicBarrier,3000);\n\n        \/\/Create and start 3 threads\n        new Thread(runnableTask1,\"Thread-1\").start();\n        new Thread(runnableTask2,\"Thread-2\").start();\n        new Thread(runnableTask3,\"Thread-3\").start();\n\n        \/*\n         * We are reusing cyclic barrier using below threads\n         * *\/\n        RunnableTask runnableTask4=new RunnableTask(cyclicBarrier,4000);\n        RunnableTask runnableTask5=new RunnableTask(cyclicBarrier,5000);\n        RunnableTask runnableTask6=new RunnableTask(cyclicBarrier,6000);\n\n        \/\/ Create and start 3 more threads\n        new Thread(runnableTask4,\"Thread-4\").start();\n        new Thread(runnableTask5,\"Thread-5\").start();\n        new Thread(runnableTask6,\"Thread-6\").start();\n\n    }\n\n}\n\n<\/pre>\n<p>Let&#8217;s run the program, then we will understand the output:<\/p>\n<div style=\"padding: 12px; background-color: #f0f8ff; line-height: 1.4;\">Thread-1 is waiting for 2 other threads to reach common barrier point<br \/>\nThread-2 is waiting for 1 other threads to reach common barrier point<br \/>\nThread-3 is waiting for 0 other threads to reach common barrier point<br \/>\nAs 3 threads have reached common barrier point ,CyclicBarrrierFinishEvent has been triggered<br \/>\nYou can update shared variables if any<br \/>\nAs 3 threads have reached common barrier point Thread-3 has been released<br \/>\nAs 3 threads have reached common barrier point Thread-1 has been released<br \/>\nAs 3 threads have reached common barrier point Thread-2 has been released<br \/>\nThread-4 is waiting for 2 other threads to reach common barrier point<br \/>\nThread-5 is waiting for 1 other threads to reach common barrier point<br \/>\nThread-6 is waiting for 0 other threads to reach common barrier point<br \/>\nAs 3 threads have reached common barrier point ,CyclicBarrrierFinishEvent has been triggered<br \/>\nYou can update shared variables if any<br \/>\nAs 3 threads have reached common barrier point Thread-6 has been released<br \/>\nAs 3 threads have reached common barrier point Thread-4 has been released<br \/>\nAs 3 threads have reached common barrier point Thread-5 has been released<\/div>\n<p>Below diagram will make you understand output better.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-2626 size-full\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/CyclicBarrierOutput-2.png\" alt=\"CyclicBarrier Output\" width=\"796\" height=\"462\" \/><\/p>\n<p>That&#8217;s all about Java CyclicBarrier example.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsDifference between CountDownLatch and CyclicBarrierJava CyclicBarrier example: In this post, we will see about CyclicBarrier in java. CyclicBarrier was introduced in Java 5 with other concurrency utils such as CountDownLatch, ConcurrentHashMap and BlockingQueue. CyclicBarrier is synchronized aid which allows set of threads to wait for each other at common barrier points.It is called [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":12649,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[212,9],"tags":[222,223],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/2621"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=2621"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/2621\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/12649"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=2621"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=2621"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=2621"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}