{"id":328,"date":"2015-08-08T13:11:00","date_gmt":"2015-08-08T13:11:00","guid":{"rendered":"http:\/\/www.java2blog.com\/?p=328"},"modified":"2021-10-18T17:17:48","modified_gmt":"2021-10-18T11:47:48","slug":"countdownlatch-in-java","status":"publish","type":"post","link":"https:\/\/java2blog.com\/countdownlatch-in-java\/","title":{"rendered":"CountDownLatch in java"},"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=\"#For_example\">For example:<\/a><ul><li><a href=\"#Program\">Program :<\/a><\/li><li><a href=\"#Why_not_use_join_instead_of_CountDownLatch\">Why not use join instead of CountDownLatch:<\/a><\/li><\/ul><\/li><\/ul><\/div>\n<div dir=\"ltr\" style=\"text-align: left;\">\n<div dir=\"ltr\" style=\"text-align: left;\">\n<div style=\"text-align: justify;\">As per java docs,\u00a0<code>CountDownLatch<\/code>\u00a0is synchronisation aid that allows one or more threads to wait until set of operations\u00a0being performed in other threads completes.<\/div\n\n\n<div style=\"text-align: justify;\">So in other words,\u00a0CountDownLatch\u00a0waits for other threads to complete set of operations.<\/div>\n<div style=\"text-align: justify;\"><\/div>\n<div style=\"text-align: justify;\">CountDownLatch is initialized with count. Any thread generally main threads calls latch.awaits() method, so it will wait for either count becomes zero or it&#8217;s interrupted by another thread and all other thread need to call <code>latch.countDown()<\/code> once they complete some operation.<\/div>\n<div style=\"text-align: justify;\"><\/div>\n<div style=\"text-align: justify;\">\n<p>So count is reduced by 1 whenever <code>latch.countDown()<\/code> method get called, so \u00a0if count is <b>n<\/b> that means count can be used as <b>n <\/b>threads have to complete some action or some action have to be completed <b>n<\/b> times.<\/p>\n<\/div>\n<div style=\"text-align: justify;\">One of disadvantage of CountDownLatch is you can not reuse it once count is zero. For that ,you need to use CyclicBarrier.<br \/>\n<!-- adsense --><\/p>\n<h3><span id=\"For_example\"><span style=\"text-align: left;\">For example:<\/span><\/span><\/h3>\n<\/div>\n<div style=\"text-align: justify;\">\n<p>Below diagram will make you clear. It is an <b>example<\/b> how CountDownLatch can be used.<\/p>\n<div style=\"text-align: justify;\"><span style=\"text-align: left;\">Let&#8217;s say, you are developing an application, so it&#8217;s main thread has to wait for other services (threads) such as UI initialization, database initialization and logging services to get completed. \u00a0So Countdownlatch will be initialized with 3 and main thread will call await() \u00a0method and each services will call latch.countDown() once they are about to complete.<\/span><\/div>\n<\/div>\n<div style=\"text-align: justify;\"><\/div>\n<div style=\"clear: both; text-align: center;\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2021\/09\/CountDownLatch.jpg\" alt=\"CountDownLatch in java\" width=\"640\" height=\"492\" border=\"0\" \/><\/div>\n<div style=\"clear: both; text-align: center;\"><\/div>\n<div style=\"clear: both; text-align: center;\"><\/div>\n<h4 style=\"text-align: left;\"><span id=\"Program\">Program :<\/span><\/h4>\n<div>Create a class named UIInitialization.java. This thread will execute latch.countDown() once it completes.<\/div>\n<pre name=\"code\">package org.arpit.java2blog.thread;\n\nimport java.util.concurrent.CountDownLatch;\n\npublic class UIInitialization implements Runnable{\n\n CountDownLatch latch;\n UIInitialization(CountDownLatch latch)\n {\n  this.latch=latch;\n }\n @Override\n public void run() {\n  System.out.println(\"Initializing UI\");\n  try {\n   Thread.sleep(3000);\n  } catch (InterruptedException e) {\n   \/\/ TODO Auto-generated catch block\n   e.printStackTrace();\n  }\n  System.out.println(\"Done with UI Initialization\");\n  latch.countDown();\n }\n\n}<\/pre>\n<p>Create a class named LoggingInitialization.java. This thread will execute latch.countDown() once it completes.<\/p>\n<\/div>\n<pre name=\"code\">package org.arpit.java2blog.thread;\n\nimport java.util.concurrent.CountDownLatch;\n\npublic class LoggingInitialization implements Runnable{\n\n CountDownLatch latch;\n LoggingInitialization(CountDownLatch latch)\n {\n  this.latch=latch;\n }\n @Override\n public void run() {\n  System.out.println(\"Initializing Logging\");\n  try {\n   Thread.sleep(2000);\n  } catch (InterruptedException e) {\n   \/\/ TODO Auto-generated catch block\n   e.printStackTrace();\n  }\n  System.out.println(\"Done with Logging Initialization\");\n  latch.countDown();\n }\n\n}<\/pre>\n<p>Create a class named DatabaseInitialization.java. This thread will execute latch.countDown() once it completes.<\/p>\n<div><\/div>\n<pre name=\"code\">package org.arpit.java2blog.thread;\n\nimport java.util.concurrent.CountDownLatch;\n\npublic class DatabaseInitialization implements Runnable{\n\n CountDownLatch latch;\n DatabaseInitialization(CountDownLatch latch)\n {\n  this.latch=latch;\n }\n @Override\n public void run() {\n  System.out.println(\"Initializing Database\");\n  try {\n   Thread.sleep(5000);\n  } catch (InterruptedException e) {\n   \/\/ TODO Auto-generated catch block\n   e.printStackTrace();\n  }\n  System.out.println(\"Done with database Initialization\");\n  latch.countDown();\n }\n\n}<\/pre>\n<p>Create a class CountDownLatchMain.java. This will be main thread which will wait for UIInitialization, DatabaseInitialization and LoggingInitialization.<\/p>\n<pre name=\"code\">package org.arpit.java2blog.thread;\n\nimport java.util.concurrent.CountDownLatch;\n\npublic class CountDownLatchMain {\n\n public static void main(String[] args) {\n  try {\n   CountDownLatch latch = new CountDownLatch(3);\n\n   \/\/ Initializing three dependent thread i.e. UI, database and logging\n\n   UIInitialization uiInitialization = new UIInitialization(latch);\n   Thread uiThread = new Thread(uiInitialization);\n\n   DatabaseInitialization dataBaseInitialization = new DatabaseInitialization(latch);\n   Thread databaseThread = new Thread(dataBaseInitialization);\n\n   LoggingInitialization loggingInitialization = new LoggingInitialization(latch);\n   Thread loggingThread = new Thread(loggingInitialization);\n\n   uiThread.start();\n   databaseThread.start();\n   loggingThread.start();\n   \/\/ Main thread will wait until above threads get completed\n   latch.await();\n\n   System.out.println(\"Initialization has been completed, main thread can proceed now\");\n  } catch (InterruptedException e) {\n\n   e.printStackTrace();\n  }\n\n }\n}\n\n<\/pre>\n<p>When you run above program, you will get following output:<\/p>\n<pre name=\"code\">Initializing UI\nInitializing Database\nInitializing Logging\nDone with Logging Initialization\nDone with UI Initialization\nDone with database Initialization\nInitialization has been completed, main thread can proceed now<\/pre>\n<h4 style=\"text-align: left;\"><span id=\"Why_not_use_join_instead_of_CountDownLatch\">Why not use join instead of CountDownLatch:<\/span><\/h4>\n<div style=\"text-align: justify;\">\n<p>As you might know you can use join for this situation too but you have to manually handles it. Most of people use [ExecutorService](https:\/\/java2blog.com\/java-executorservice-example-using-callable-future\/ &#8220;ExecutorService&#8221;) for handling threads now and CountDownLatch works good with it. As CountDownLatch is task oriented , you can submit multiple tasks to thread pool and CountDownLatch will ensure execution of original thread once set of other \u00a0dependent threads get completed.<\/p>\n<p><span style=\"text-align: left;\">Please go through\u00a0<\/span><span style=\"text-align: left;\">\u00a0<\/span><a style=\"text-align: left;\" href=\"http:\/\/www.java2blog.com\/core-java-interview-questions-and-answers\/\" target=\"_blank\" rel=\"noopener noreferrer\">top 50 core java interview questions<\/a><span style=\"text-align: left;\">\u00a0for more interview questions.<\/span><\/p>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsFor example:Program :Why not use join instead of CountDownLatch: As per java docs,\u00a0CountDownLatch\u00a0is synchronisation aid that allows one or more threads to wait until set of operations\u00a0being performed in other threads completes.<\/p>\n","protected":false},"author":1,"featured_media":12643,"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\/328"}],"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=328"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/328\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/12643"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=328"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=328"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=328"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}