日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

JAVA-Concurrency之CountDownLatch说明

發布時間:2023/12/9 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JAVA-Concurrency之CountDownLatch说明 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

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 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.

  • 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.
  • 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.
  • 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

    總結

    以上是生活随笔為你收集整理的JAVA-Concurrency之CountDownLatch说明的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

    主站蜘蛛池模板: 综合五月激情 | 哪里看毛片 | 日韩伦人妻无码 | 国产精品亚洲一区二区无码 | 午夜资源网 | 黄免费在线观看 | 成年午夜视频 | 农村脱精光一级 | 91视频免费看片 | 欧美色涩 | 性一交一乱一色一视频麻豆 | 久操视频网站 | 天天操天天操天天射 | 欧美一级在线免费观看 | 性――交――性――乱睡觉 | 国产精品久久久99 | 亚洲精品一区二区三区不卡 | 香蕉在线观看视频 | 久久一本精品 | 韩国日本美国免费毛片 | 超碰超碰超碰超碰超碰 | 欧美精品四区 | 欧美黄网站 | 中国av一区二区 | 制服丝袜中文字幕在线 | 色午夜| a在线视频 | 欧美人妻一区二区 | 合欢视频污| 一本一道久久综合 | 日批黄色 | 欧美成人一区二区三区高清 | 善良的公与媳hd中文字 | 中文字幕乱码中文字幕 | 中文字幕理论片 | 国产亚洲激情 | 久久色视频 | 女性女同性aⅴ免费观女性恋 | 可以免费观看的av | 一二三av | 在线免费观看黄网站 | 国产精品怡红院 | 香蕉91视频 | 嫩草www| 久久久999视频 | 深夜视频免费在线观看 | 99re在线| 麻豆精品在线看 | 日产精品久久久久久久蜜臀 | 中文字幕av免费观看 | 久草国产视频 | 欧美黑人狂野猛交老妇 | 欧美专区第二页 | 精品无码久久久久久国产 | 夜夜爽日日澡人人添 | 亚洲色图一区二区 | 隔壁邻居是巨爆乳寡妇 | 亚洲一级二级片 | 美女扒开尿口给男人桶 | 超碰毛片 | 青青草在线视频免费观看 | 日韩三区在线 | 香蕉a视频| 五月婷婷六月色 | 久操社区 | 末发成年娇小性xxxxx | 亚洲精品一区二区三区婷婷月 | 香蕉视频网页版 | 久草高清视频 | 色综合中文网 | 天天久久久 | 午夜一区二区三区在线观看 | 无码h肉动漫在线观看 | 影音先锋啪啪资源 | 九九综合九九综合 | 一区二区精品国产 | 久久丫精品 | 久久久久久久国产精品毛片 | 国产调教| 99久久久无码国产精品衣服 | 日韩爱爱视频 | 粉嫩av| www.99色| 女人高潮娇喘声mp3 乱色视频 | 日本美女裸体视频 | 一个色在线视频 | 都市激情男人天堂 | mdyd—856冲田杏梨在线 | 午夜播放 | 日韩av高清无码 | 人妻无码一区二区三区久久99 | 手机成人av在线 | 欧美日韩国产a | 免费三级网| 深夜福利视频导航 | 日韩专区第一页 | 黄色精品一区 | 少妇熟女视频一区二区三区 | 国产九九久久 |