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.mzph.cn/news/278197.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

设置微软应用商店的代理_如何设置和使用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

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;分享给…

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…

深入分析 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…

为什么无法运行谷歌play_什么是Google Play积分,以及如何使用它们?

为什么无法运行谷歌playThe Google Play Store is home to thousands of apps, games, movies, e-books, and more. You might find yourself making a lot of purchases there, so why not get rewarded for it? That’s where Google Play Points come in. Google Play商店提…

2019年春季学期第三周作业

本周作业 本周请大家完成上周挑战作业的第一部分&#xff1a;给定一个整数数组(包含正负数)&#xff0c;找到一个具有最大和的子数组&#xff0c;返回其最大的子数组的和。 例如&#xff1a;[1, -2, 3, 10, -4, 7, 2, -5]的最大子数组为[3, 10, -4, 7, 2] 1&#xff09;.实验代…

Linux实验二:linux 常用命令练习

ls命令 列出目录内容 echo命令 显示字符串 date命令 显示或设置系统的日期与时间 cal命令 显示日历 who命令 列出登录用户信息 chown命令 chgrp命令 改变文件所属的用户组 chmod命令 改变文件访问权限 find命令 在目录中搜索文件 转载于:https://www.cnblogs.com/nullno/p/87…

短语密码_使用密码短语以提高安全性

短语密码Did you know that Windows supports using passwords of up to 127 characters? I don’t use passwords anymore, and I haven’t for years. I’ve switched to using password phrases instead. 您知道Windows支持使用最多127个字符的密码吗&#xff1f; 我不再使…