`
cywhoyi
  • 浏览: 418600 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

What is CountDownLatch?

    博客分类:
  • JAVA
 
阅读更多

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

//
you're reading...

CORE JAVA,INTERVIEW,JAVA 5 FEATURES,MULTI THREADING

When to use CountDownLatch : Java concurrency example tutorial

<iframe id="_mN_main_811861174_0_n" style="margin: 0px; padding: 0px; border-width: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline;" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="728" height="90"></iframe>

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 question in 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:

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

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.

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.

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.

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 latch
	public BaseHealthChecker(String serviceName, CountDownLatch latch) {
		super();
		this._latch = latch;
		this._serviceName = serviceName;
		this._serviceUp = false;
	}

	@Override
	public 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 checker
	public abstract void verifyService();
}

 

public class ApplicationStartupUtil {
	// List of service checkers
	private static List<BaseHealthChecker> _services;

	// This latch will be used to wait on
	private 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 framework
		Executor 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 startup
		for (final BaseHealthChecker v : _services) {
			if (!v.isServiceUp()) {
				return false;
			}
		}
		return true;
	}
}

 

public class CacheHealthChecker extends BaseHealthChecker {
	public CacheHealthChecker(CountDownLatch latch) {
		super("CACHE Service", latch);
	}

	@Override
	public void verifyService() {
		System.out.println("Checking " + this.getServiceName());
		try {
			Thread.sleep(7000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(this.getServiceName() + " is UP");
	}

}

 

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);
	}
}

 

分享到:
评论

相关推荐

    JAVA多线程CountDownLatch使用详解

    什么时候用CountDownLatch? 在多线程编程中,我们经常会遇到这样一种情况:某个线程需要等待其他线程执行完毕后再继续执行。例如,在上面的代码中,我们需要让MyThread1线程先运行完毕,然后MyThread线程再继续...

    多线程countDownLatch方法介绍

    在Java多线程编程中,CountDownLatch是一个非常重要的同步工具类,它可以帮助我们协调多个线程之间的交互。本文将深入探讨CountDownLatch的工作原理、使用场景以及相关源码分析。 CountDownLatch是一个计数器,初始...

    CountDownLatch练习

    CountDownLatch是Java并发编程中一个重要的同步工具类,它允许一个或多个线程等待其他线程完成操作。这个工具在多线程环境下的并行处理和协调中扮演着关键角色。 **CountDownLatch是什么?** CountDownLatch是一个...

    CountDownLatch和CyclicBarrier用法实例大全

    在Java并发编程中,CountDownLatch和CyclicBarrier是两种非常重要的同步工具类,它们用于协调多个线程间的协作。这两个工具都是在`java.util.concurrent`包下,是Java并发库的重要组成部分。 **CountDownLatch** ...

    利用 CountDownLatch 类实现线程同步

    Java 提供了多种工具来实现这样的同步机制,其中之一便是 `CountDownLatch` 类。`CountDownLatch` 是一个计数器,可以用于协调多个线程间的活动,等待所有线程完成各自的任务后,主线程或其他线程才能继续执行。 ...

    CountDownLatch学习用法

    CountDownLatch是Java并发编程中一个重要的工具类,它属于java.util.concurrent包下的一个同步辅助类。这个类的设计目的是允许一个线程等待其他多个线程完成操作,然后再继续执行。CountDownLatch通常用于多线程协作...

    java并发编程中CountDownLatch和CyclicBarrier的使用借鉴.pdf

    java并发编程中CountDownLatch和CyclicBarrier的使用借鉴 java并发编程中CountDownLatch和CyclicBarrier是两个非常重要的线程控制和调度工具,经常被用于解决多线程程序设计中的线程等待问题。本文将对...

    CountDownLatch的使用

    递减锁存器CountDownLatch的使用以及注意事项!

    mybaits 多线程 实现数据批量插入 (运用CountDownLatch实现闭锁)

    本文将详细介绍如何利用MyBatis结合多线程和CountDownLatch闭锁来实现数据的批量插入。 首先,我们来看`mybatis批处理`。MyBatis的批处理功能允许我们在一次数据库连接中执行多条SQL语句,从而减少了数据库连接的...

    CountDownLatch与thread.join()的区别

    CountDownLatch与thread.join()的区别

    并发编程之CountDownLatch

    CountDownLatch 并发编程 CountDownLatch 是一个同步的辅助类,它可以允许一个或多个线程等待,直到一组在其它线程中的操作执行完成。它通过一个计数器来实现的,计数器的初始值为线程的数量。每当一个线程完成了...

    CountDownLatch Demo

    CountDownLatch 是 Java 多线程并发编程中一个重要的同步工具类,主要用来协调多个线程间的协作,确保某个任务在所有线程完成之前不会开始。在这个"CountDownLatch Demo"中,我们将深入理解 CountDownLatch 的原理、...

    CountDownLatch详解.docx

    CountDownLatch 是 Java 中的一个同步工具类,位于 `java.util.concurrent` 包下,它主要用于多线程间的协作,尤其在需要等待所有线程执行完指定任务后才能继续执行的情况。这个类通过一个计数器(计数down)来实现...

    countdownlatch-example-sourcecode.zip

    《CountDownLatch实战解析与源码探索》 CountDownLatch是Java并发编程中一个非常重要的同步工具类,它在多线程协作场景中起到了关键的作用。在`countdownlatch-example-sourcecode.zip`这个压缩包中,我们可以看到...

    Java中CountDownLatch进行多线程同步详解及实例代码

    Java中CountDownLatch进行多线程同步详解及实例代码 CountDownLatch是Java中的一种多线程同步辅助类,主要用来同步多个任务的执行。它允许一个或多个线程等待,直到一组正在其他线程中执行的操作完成。下面是对...

    Java中CountDownLatch用法解析

    在Java并发编程中,`CountDownLatch`是一个非常重要的工具类,它位于`java.util.concurrent`包下,用于协调多个线程间的同步。`CountDownLatch`的主要作用是允许一个或多个线程等待其他线程完成操作。在上述例子中,...

    CountDownLatch同步工具类使用详解

    CountDownLatch同步工具类使用详解 CountDownLatch是一个java.util.concurrent包下的同步工具类,它允许一个或多个线程等待直到在其他线程中一组操作执行完成。CountDownLatch的用法非常简单,它可以用来控制线程的...

    Java concurrency之CountDownLatch原理和示例_动力节点Java学院整理

    CountDownLatch是Java并发编程中一个重要的工具类,用于协调多线程间的同步。它由Java并发包`java.util.concurrent`提供,主要用于解决一种场景:在主控线程等待多个子线程完成各自任务后再继续执行的情况。下面我们...

    如何使用CountDownLatch同步java多线程

    如何使用CountDownLatch同步java多线程 CountDownLatch 是 Java 并发编程中的一种常用工具,用于控制多个线程的并发执行。它可以实现多个线程之间的同步操作,使得线程之间可以协调工作,避免了线程之间的互相干扰...

    Java并发包之CountDownLatch用法.docx

    `CountDownLatch`是Java并发包`java.util.concurrent`中的一个重要工具类,用于实现线程间的同步。它基于计数器的概念,初始化时设置一个非负的计数值,然后通过调用`countDown()`方法来递减这个计数器。主线程或...

Global site tag (gtag.js) - Google Analytics