JAVA-Concurrency之CountDownLatch說明

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

As per java docs,?CountDownLatch?is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. CountDownLatch concept is very common?interview questionin?java concurrency, so make sure you understand it well. In this post, I will cover following points related to CountDownLatch in java concurrency.

Sections in this post:What is CountDownLatch?
How CountDownLatch works?
Possible usages in real time applications
Example application
Common interview questions

What is CountDownLatch?

CountDownLatch was?introduced with JDK 1.5 along with other concurrent utilities like CyclicBarrier, Semaphore,?ConcurrentHashMap?and?BlockingQueue?in java.util.concurrent package. This class?enables a java thread to wait until other set of threads completes?their tasks. e.g. Application’s main thread want to wait, till other service threads which are responsible for starting framework services have completed started all services.

CountDownLatch works by having a counter initialized with number of threads, which is decremented each time a thread complete its execution. When count reaches to zero, it means all threads have completed their execution, and thread waiting on latch resume the execution.

CountdownLatch

CountDownLatch Concept

Pseudo code for CountDownLatch can be written like this:

//Main thread start
//Create CountDownLatch for N threads
//Create and start N threads
//Main thread wait on latch
//N threads completes there tasks are returns
//Main thread resume execution

How CountDownLatch works?

CountDownLatch.java class defines one constructor inside:

//Constructs a CountDownLatch initialized with the given count.public?CountDownLatch(int?count) {...}


The first interaction with CountDownLatch is with main thread which is goind to wait for other threads. This main thread must call,?CountDownLatch.await()?method immediately after starting other threads. The execution will stop on await() method till the time, other threads complete their execution.This?count is essentially the number of threads, for which latch should wait. This value can be set only once, and CountDownLatch provides?no other mechanism to reset this count.

Other N threads must have reference of latch object, because they will need to notify the CountDownLatch object that they have completed their task. This notification is done by method :?CountDownLatch.countDown(); Each invocation of method decreases the initial count set in constructor, by 1. So, when all N threads have call this method, count reaches to zero, and main thread is allowed to resume its execution past await() method.

Possible usages in real time applications

Let’s try to identify some possible usage of CountDownLatch in real time java applications. I am listing, as much i can recall. If you have any other possible usage, please leave a comment. It will help others.

  1. Achieving Maximum Parallelism?: Sometimes we want to start a number of threads at the same time to achieve maximum parallelism. For example, we want to test a class for being singleton. This can be done easily if we create a CountDownLatch with initial count 1, and make wait all threads to wait of latch. A single call to countDown() method will resume execution for all waiting threads in same time.
  2. Wait N threads to completes before start execution: For example an application start-up class want to ensure that all N external systems are Up and running before handling the user requests.
  3. Deadlock detection: A very handy use case in which you can use N threads to access a shared resource with different number of threads in each test phase, and try to create a deadlock.

Example application using CountDownLatch

In this example, I have simulated an application startup class which starts N threads that will check for external systems and report back to latch, on which startup class is waiting. As soon as all services are verified and checked, startup proceeds.

BaseHealthChecker.java?: This class is a Runnable and parent for all specific external service health checkers. This remove the code duplicacy and central control over latch.

public?abstract?class?BaseHealthChecker?implements?Runnable {private?CountDownLatch _latch;private?String _serviceName;private?boolean?_serviceUp;//Get latch object in constructor so that after completing the task, thread can countDown() the latchpublic?BaseHealthChecker(String serviceName, CountDownLatch latch){super();this._latch = latch;this._serviceName = serviceName;this._serviceUp =?false;}@Overridepublic?void?run() {try?{verifyService();_serviceUp =?true;}?catch?(Throwable t) {t.printStackTrace(System.err);_serviceUp =?false;}?finally?{if(_latch !=?null) {_latch.countDown();}}}public?String getServiceName() {return?_serviceName;}public?boolean?isServiceUp() {return?_serviceUp;}//This methos needs to be implemented by all specific service checkerpublic?abstract?void?verifyService();}

NetworkHealthChecker.java?:

This class extends BaseHealthChecker and needs to provide only implementation of verifyService() method.?DatabaseHealthChecker.java?and?CacheHealthChecker.java?are same as NetworkHealthChecker.java apart from their service names and sleep time.

public?class?NetworkHealthChecker?extends?BaseHealthChecker{public?NetworkHealthChecker (CountDownLatch latch)? {super("Network Service", latch);}@Overridepublic?void?verifyService(){System.out.println("Checking "?+?this.getServiceName());try{Thread.sleep(7000);}catch?(InterruptedException e){e.printStackTrace();}System.out.println(this.getServiceName() +?" is UP");}}

ApplicationStartupUtil.java?: This clas is main startup class which initilizes the latch and wait of this latch till all services are checked.

public?class?ApplicationStartupUtil{//List of service checkersprivate?static?List<BaseHealthChecker> _services;//This latch will be used to wait onprivate?static?CountDownLatch _latch;private?ApplicationStartupUtil(){}private?final?static?ApplicationStartupUtil INSTANCE =?new?ApplicationStartupUtil();public?static?ApplicationStartupUtil getInstance(){return?INSTANCE;}public?static?boolean?checkExternalServices()?throws?Exception{//Initialize the latch with number of service checkers_latch =?new?CountDownLatch(3);//All add checker in lists_services =?new?ArrayList<BaseHealthChecker>();_services.add(new?NetworkHealthChecker(_latch));_services.add(new?CacheHealthChecker(_latch));_services.add(new?DatabaseHealthChecker(_latch));//Start service checkers using executor frameworkExecutor executor = Executors.newFixedThreadPool(_services.size());for(final?BaseHealthChecker v : _services){executor.execute(v);}//Now wait till all services are checked_latch.await();//Services are file and now proceed startupfor(final?BaseHealthChecker v : _services){if( ! v.isServiceUp()){return?false;}}return?true;}}

Now you can write any test class to check the functionality of latch.

public?class?Main {public?static?void?main(String[] args){boolean?result =?false;try?{result = ApplicationStartupUtil.checkExternalServices();}?catch?(Exception e) {e.printStackTrace();}System.out.println("External services validation completed !! Result was :: "+ result);}}
Output in console:Checking Network ServiceChecking Cache ServiceChecking Database ServiceDatabase Service is UPCache Service is UPNetwork Service is UPExternal services validation completed !! Result was ::?true


Be prepared to face these questions related to CountDownLatch in your next interview.Common interview questions

  • Explain the concept of CountDownLatch?
  • Difference between CountDownLatch and CyclicBarrier?
  • Give some example uses of CountDownLatch?
  • What are main methods CountDownLatch class has?

To Download the sourcecode of above example application follow given link.

轉載于:https://my.oschina.net/xiehongfei/blog/1789815

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/278197.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/278197.shtml
英文地址,請注明出處:http://en.pswp.cn/news/278197.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

windows下共享文件夾在Linux下打開

①首先在Windows下創建一個準備用來共享用的文件夾 ②在虛擬機下選擇第一步創建的文件夾為共享文件夾 ③在虛擬機shell命令框下輸入 cd /mnt/sgfs 回車進入共享文件夾。 備注&#xff1a;其他細節與配圖后續再更新 Thanks轉載于:https://www.cnblogs.com/better-day/p/105026…

設置微軟應用商店的代理_如何設置和使用Microsoft家庭安全應用

設置微軟應用商店的代理The Microsoft Family Safety app provides a set of reporting and parental control tools for people with Microsoft accounts. With filtering controls, location reporting, and app-usage recording, this app gives parents a way to monitor t…

Linux跨平臺遠程控制

轉載于:https://blog.51cto.com/13660858/2094987

20189222 《網絡攻防實踐》第二周作業

20189222《網絡攻防實踐》第2周學習總結 教材學習內容總結 第一章&#xff1a; 要點1&#xff1a;分清黑客與駭客&#xff0c;提倡在掌握技術的同時&#xff0c;還要遵循黑客道德與法律法規。 要點2&#xff1a;網絡攻防的主要內容包括系統安全攻防、網絡安全攻防、物理攻擊和社…

Zoom Host可以真正看到您的所有私人消息嗎?

Girts Ragelis/Shutterstock.comGirts Ragelis / Shutterstock.comViral social media posts are alleging that Zoom’s private messages aren’t really private—if you’re chatting privately during a Zoom meeting, the host can see your entire conversation. Is tha…

使用Keras進行深度學習:(三)使用text-CNN處理自然語言(上)

歡迎大家關注我們的網站和系列教程&#xff1a;http://www.tensorflownews.com/&#xff0c;學習更多的機器學習、深度學習的知識&#xff01; 上一篇文章中一直圍繞著CNN處理圖像數據進行講解&#xff0c;而CNN除了處理圖像數據之外&#xff0c;還適用于文本分類。CNN模型首次…

powerpoint轉換器_如何將PowerPoint演示文稿轉換為主題演講

powerpoint轉換器If someone sends you a Microsoft PowerPoint presentation, but you’d rather use Apple’s presentation software, Keynote, you’re in luck! Apple’s done all the hard work for you. Here’s how to convert a PowerPoint presentation to Keynote. …

Android高仿大眾點評(帶服務端)

2019獨角獸企業重金招聘Python工程師標準>>> 實例講解了一個類似大眾點評的項目&#xff0c;項目包含服務端和android端源碼, 服務端為php代碼&#xff0c;如果沒有接觸過php, 文章中講解一鍵部署php的方法&#xff0c;讓您5分鐘將服務端搭建成功, 您也可以將php換成…

vista任務欄透明_在Windows XP中獲取Vista任務欄縮略圖預覽

vista任務欄透明It was only a matter of time before people started cloning Windows Vista features and adding them into Windows XP. One of my favorite Vista features is the thumbnails that popup when you mouse over the taskbar. And now I can use them in XP a…

Spring實戰Day2

創建對象之后如何體現對象之間的依賴&#xff1f; Spring容器負責創建Bean和依賴注入&#xff0c;那么Spring是怎么將Bean裝配在一起的呢&#xff1f; Spring提供了三種方式裝配機制 1.隱式的bean發現機制和自動裝配 圖一圖二&#xff0c;是兩個組件與Config類同包 圖三&#x…

Git的狀態轉換

近期公司用Git來管理代碼&#xff0c;用起來是要比svn爽一些。就是剛接觸的時候比較痛苦&#xff0c;特別是那些狀態(版本號的提交/合并/回退)。差點把我搞暈了。如今回過頭來總結一下&#xff0c;就清楚多了。 就本地倉庫來看。Git能夠分成5個不同的狀態。能夠通過$ git statu…

RN自定義組件封裝 - 播放類似PPT動畫

1. 前言 近日&#xff0c;被安排做一個開場動畫的任務。雖然RN提供了Animated來自定義動畫&#xff0c;但是本次動畫中的元素頗多&#xff0c;交互甚煩。。。在完成任務的同時&#xff0c;發現很多步驟其實是重復的&#xff0c;于是封裝了一個小組件記錄一下&#xff0c;分享給…

target存放的是編譯后的.class文件地方 默認情況下不會講非class文件放入進入 如果要使用非.class文件 需要通過增加配置方式自動加入文件...

target存放的是編譯后的.class文件地方 默認情況下不會講非class文件放入進入 如果要使用非.class文件 需要通過增加配置方式自動加入文件轉載于:https://www.cnblogs.com/classmethond/p/10520615.html

dropbox mac_如何在Windows或Mac上啟動時阻止Dropbox打開

dropbox macDropbox is a handy way to synchronize files across devices via the cloud. By default, Dropbox starts whenever you turn on your Windows PC or Mac, but sometimes you might not want it to. Here’s how to make sure it doesn’t launch when you startu…

spring cloud 總結

Finchley版本Spring Cloud Finchley; Spring Boot 2.0.3 史上最簡單的 SpringCloud 教程 | 第一篇: 服務的注冊與發現&#xff08;Eureka&#xff09;(Finchley版本) 所有的服務向這里注冊 史上最簡單的SpringCloud教程 | 第二篇: 服務消費者&#xff08;restribbon&#xff09…

深入分析 ThreadLocal 內存泄漏問題

2019獨角獸企業重金招聘Python工程師標準>>> ThreadLocal 的作用是提供線程內的局部變量&#xff0c;這種變量在線程的生命周期內起作用&#xff0c;減少同一個線程內多個函數或者組件之間一些公共變量的傳遞的復雜度。但是如果濫用 ThreadLocal&#xff0c;就可能會…

如何將iPhone應用程序從應用程序庫移動到主屏幕

Justin Duino賈斯汀杜伊諾(Justin Duino)So as to not clutter up your home screen, newly-downloaded apps from the App Store can be sent directly to the App Library. But what if you later want to open the app without digging through the library? Here’s how t…

luogu4389 付公主的背包

題目鏈接&#xff1a;洛谷 題目大意&#xff1a;現在有$n$個物品&#xff0c;每種物品體積為$v_i$&#xff0c;對任意$s\in [1,m]$&#xff0c;求背包恰好裝$s$體積的方案數&#xff08;完全背包問題&#xff09;。 數據范圍&#xff1a;$n,m\leq 10^5$ 這道題&#xff0c;看到…

Git與Github的連接與使用

2019獨角獸企業重金招聘Python工程師標準>>> Git與Github的連接與使用 下面繼續&#xff0c;使用git 將項目上傳到GitHub上 首先要有GitHub賬號,這就不用說了&#xff0c;沒有的先注冊&#xff0c;地址&#xff1a;https://github.com 沒有倉庫的話&#xff0c;先新…

ttl電路制作pong游戲_如何玩Mozilla Firefox的隱藏的獨角獸Pong游戲

ttl電路制作pong游戲It seems like every browser has a hidden game these days. Chrome has a dinosaur game, Edge has surfing, and Firefox has . . . unicorn pong? Yep, you read that right—here’s how to play it. 這些天似乎每個瀏覽器都有一個隱藏的游戲。 Chrom…