CountDownLatch 란?
공식문서 설명
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.
A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes. A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown(). A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.
A useful property of a CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.
동기화 지원 도구로 다른 스레드에서 연산들의 집합이 끝날 때까지 기다리게 해줍니다.
모든 대기중인 스레드가 릴리즈되고 이어지는 await()
호출 이후에 latch.countDown()
에 의해 count
가 0
에 도달할 때까지 해당 스레드의 동작을 블록합니다.
이 것은 한 번만 일어나는 현상이고, count
는 다시 재설정될 수 없습니다. 만일 카운트를 재설정하는 버전이 필요하다면, CyclicBarrier
를 사용하세요.
예제 코드
public class CountDownLatchTest {
private final static int THREADS = 10;
private static CountDownLatch lacth = new CountDownLatch(THREADS);
public static class RandomSleepRunnable implements Runnable {
private int id = 0;
private static Random random = new Random(System.currentTimeMillis());
public RandomSleepRunnable(int id) {
this.id = id;
}
@Override
public void run() {
System.out.println("Thread(" + id + ") : Start."); // 1000ms 에서 2000ms 사이의 딜레이 값을 랜덤하게 생성.
int delay = random.nextInt(1001) + 1000;
try {
System.out.println("Thread(" + id + ") : Sleep " + delay + "ms");
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread(" + id + ") : End."); // lacth 의 카운터에서 -1.
lacth.countDown();
}
}
@Test
public void countDownLatchTest() {
// 쓰레드를 10개 생성.
for (int i = 0; i < THREADS; ++i) {
new Thread(new RandomSleepRunnable(i)).start();
}
try {
// lacth 의 카운트가 0이 될 때 까지 대기한다.
lacth.await();
// 아래와 같이 TimeOut 을 설정할 수 있다.
// 아래의 경우는, 만약 2000ms 동안 latch 의 카운트가 0 되지 않는다면
// wait 상태를 해제하고 다음 동작으로 넘어간다.
// lacth.await(2000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads terminated.");
}
}
레퍼런스
join과의 차이
join() is waiting for another thread to finish while CountDownLatch is designed for another purpose. If using CountDownLatch, You don't have to have reference of threads for which you are waiting as we have to do using join(). Let's assume you want to start a game when at least 2 players should be available. You can use countdownlatch in this case. But you can't achieve this using join easily because you don't have another thread(player in this case) on which you can write join().
Another difference is after join(), thread can be unblocked only when joined thread has finished its execution while in CountDownLatch a thread can decrease the count anytime either on completion of thread or in between based on any condition.
This way we can get better control over unblocking of the thread instead of solely depending on the completion of joined thread.
CountDownLatch
가 훨씬 유연하고 사용하기 좋다.join()
메서드처럼 스레드의 참조가 필요 없다.- 스레드가 끝나기 전에도
countDown()
은 실행 가능하기 때문에, 스레드에서 원하는 타이밍에count
를 줄여서 유연하게 쓸 수도 있다.
'Java > 자바 API' 카테고리의 다른 글
자바 Objects.requireNonNull() 을 사용하는 이유 (1) | 2023.11.06 |
---|---|
자바 스트링 풀에 대해 쉽게 이해하기 (0) | 2021.12.25 |
자바 WeakMap 쉽게 알아보기 (0) | 2021.12.23 |