Spring
API
동시성 관련

동시성 관련 제어 모듈

ExecutorService

각기 다른 Thread를 생성하고 관리하는 클래스. 생성, 실행, 제거에 대한 전체적인 로직을 수행해줄 수 있다.

ExecutorService 생성

ExecutorService executorService = Executors.newFixedThreadPool(10);
ExecutorService executorService = Executors.newCachedThreadPool();
ExecutorService executorService = Executors.newSingleThreadExecutor();
  • newFixedThreadPool : 고정된 개수의 Thread를 생성하고 관리한다.
  • newCachedThreadPool : 필요에 따라 Thread를 생성하고 관리한다.
  • newSingleThreadExecutor : 하나의 Thread만 생성하고 관리한다.

Task에 일 시키기

  1. execute() : 리턴 타입이 void로 Task의 실행 결과나 Task의 상태를 알 수 없다.
  2. submit() : Task를 할당하고 Future 타입의 결과값을 받는다. 결과 리턴이 되야해서 Callable을 구현한 Task를 인자로 준다.
  3. invokeAny() : Task를 Collection에 넣어서 인자로 넘겨준다. 실행에 성공한 Task 중 하나의 결과값을 반환한다.
  4. invokeAll() : Task를 Collection에 넣어서 인자로 넘겨줄 수 있다. 모든 Task의 리턴값을 List<Future> 타입으로 반환한다.

예제 코드

int threadCount = 100;
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
CountDownLatch latch = new CountDownLatch(threadCount);
 
for (int i = 0; i < threadCount; i++) {
    long userId = i;
    // ExecutorService에 Task를 할당한다.
    executorService.submit(() -> {
                try {
                    applyService.apply(userId);
                } finally {
                    latch.countDown();
                }
            }
    );
}
latch.await();
long count = couponRepository.count();