반응형
Jake Seo
제이크서 위키 블로그
Jake Seo
전체 방문자
오늘
어제
  • 분류 전체보기 (715)
    • 일상, 일기 (0)
    • 백준 문제풀이 (1)
    • 릿코드 문제풀이 (2)
    • 알고리즘 이론 (10)
      • 기본 이론 (2)
      • 배열과 문자열 (8)
    • 데이터베이스 (15)
      • Planet Scale (1)
      • MSSQL (9)
      • 디비 기본 개념 (1)
      • SQLite 직접 만들어보기 (4)
    • 보안 (7)
    • 설계 (1)
    • 네트워크 (17)
      • HTTP (9)
      • OSI Layers (5)
    • 회고 (31)
      • 연간 회고 (2)
      • 주간 회고 (29)
    • 인프라 (52)
      • 도커 (12)
      • AWS (9)
      • 용어 (21)
      • 웹 성능 (1)
      • 대규모 서비스를 지탱하는 기술 (9)
    • 깃 (7)
    • 빌드 도구 (7)
      • 메이븐 (6)
      • 그레이들 (0)
    • Java (135)
      • 이펙티브 자바 (73)
      • 자바 API (4)
      • 자바 잡지식 (30)
      • 자바 디자인 패턴 (21)
      • 톰캣 (Tomcat) (7)
    • 프레임워크 (64)
      • next.js (14)
      • 스프링 프레임워크 (28)
      • 토비의 스프링 (6)
      • 스프링 부트 (3)
      • JPA (Java Persistence API) (5)
      • Nest.js (8)
    • 프론트엔드 (48)
      • 다크모드 (1)
      • 노드 패키지 관리 매니저 (3)
      • CSS (19)
      • Web API (11)
      • tailwind-css (1)
      • React (5)
      • React 새 공식문서 요약 (1)
      • HTML (Markup Language) (5)
    • 자바스크립트 (108)
      • 모던 자바스크립트 (31)
      • 개념 (31)
      • 정규표현식 (5)
      • 코드 스니펫 (1)
      • 라이브러리 (6)
      • 인터뷰 (24)
      • 웹개발자를 위한 자바스크립트의 모든 것 (6)
      • 팁 (2)
    • Typescript (49)
    • 리눅스와 유닉스 (10)
    • Computer Science (1)
      • Compiler (1)
    • IDE (3)
      • VSCODE (1)
      • IntelliJ (2)
    • 세미나 & 컨퍼런스 (1)
    • 용어 (개발용어) (16)
      • 함수형 프로그래밍 용어들 (1)
    • ORM (2)
      • Prisma (2)
    • NODEJS (2)
    • cypress (1)
    • 리액트 네이티브 (React Native) (31)
    • 러스트 (Rust) (15)
    • 코틀린 (Kotlin) (4)
      • 자바에서 코틀린으로 (4)
    • 정규표현식 (3)
    • 구글 애널리틱스 (GA) (1)
    • SEO (2)
    • UML (2)
    • 맛탐험 (2)
    • 리팩토링 (1)
    • 서평 (2)
    • 소프트웨어 공학 (18)
      • 테스팅 (16)
      • 개발 프로세스 (1)
    • 교육학 (1)
    • 삶의 지혜, 통찰 (1)
    • Chat GPT (2)
    • 쉘스크립트 (1)
    • 컴파일 (2)
    • Dart (12)
    • 코드팩토리의 플러터 프로그래밍 (4)
    • 플러터 (17)
    • 안드로이드 스튜디오 (1)
    • 윈도우즈 (1)
    • 잡다한 백엔드 지식 (1)
    • 디자인 패턴 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 팩터리 메서드 패턴
  • next js app
  • 객체복사
  • 플라이웨이트패턴
  • 싱글턴
  • serverless computing
  • 메이븐 골
  • 싱글톤
  • 추상 팩터리 패턴
  • 메이븐 라이프사이클
  • 도커공식문서
  • item7
  • 느린 쿼리
  • 자료구조
  • 자바스크립트 면접
  • 작업기억공간
  • 자바 디자인패턴
  • 자바
  • try-with-resources
  • pnpm
  • 프로그래머의 뇌
  • 이펙티브자바
  • prerendering
  • Pre-rendering
  • 자바스크립트 인터뷰
  • 러스트
  • bean Validation
  • 서버리스 컴퓨팅
  • Java
  • 싱글톤 패턴
  • 자바스크립트
  • 외래키 제약조건
  • item8
  • 알고리즘
  • Javadoc 자바독 자바주석 주석 Comment
  • 이펙티브 자바
  • 슬로우 쿼리
  • 빈 검증
  • 이펙티브 자바 item9
  • 스프링 검증
  • NEXT JS
  • rust
  • 참조 해제
  • MSSQL
  • 자바 검증
  • 디자인패턴
  • 메이븐 페이즈
  • 토비의 스프링
  • item9
  • Next.js

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Jake Seo

제이크서 위키 블로그

Java/자바 API

자바 CountDownLatch란?

2022. 1. 3. 20:21

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

레퍼런스

https://dev.re.kr/52

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
    'Java/자바 API' 카테고리의 다른 글
    • 자바 Objects.requireNonNull() 을 사용하는 이유
    • 자바 스트링 풀에 대해 쉽게 이해하기
    • 자바 WeakMap 쉽게 알아보기
    Jake Seo
    Jake Seo
    ✔ 잘 보셨다면 광고 한번 클릭해주시면 큰 힘이 됩니다. ✔ 댓글로 틀린 부분을 지적해주시면 기분 나빠하지 않고 수정합니다. ✔ 많은 퇴고를 거친 글이 좋은 글이 된다고 생각합니다. ✔ 간결하고 명료하게 사람들을 이해 시키는 것을 목표로 합니다.

    티스토리툴바