package sample;
import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
public class SampleTest {
private AtomicInteger counter = new AtomicInteger(0);
public void increment() {
counter.incrementAndGet();
}
@Test
public void testConcurrency() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
executorService.submit(this::increment);
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
assertEquals(1000, counter.get(), "1000이여야만 합니다.");
}
}
- Thread수가 10개로 고정된 스레드풀을 관리하는 ExcecutorService 객체를 생성하고,
- 원자적 작업 수행을 보장하는 AtomicInteger 타입 객체를 통하여, 스레드풀에서의 작업을 1000번의 increment한 작업을 하게끔 함.
- 마지막 assertEquals를 통하여, thread-safe하게 1,000번의 작업을 했는지 검증하게끔 함.
+) ExecutorService는 다중 스레드 환경에서 작업을 비동기적으로 관리하고 스레드를 효율적으로 사용할 수 있도록 도와주는 클래스.
submit() 또는 execute() 메서드를 사용해 비동기적으로 실행할 작업을 ExecutorService에 제출할 수 있음.
메인 스레드가 블로킹 없이 다른 작업을 계속 수행할 수 있고, 동시에 여러 작업을 처리하는 멀티스레딩 환경에서 유용함.
728x90
반응형
'TDD' 카테고리의 다른 글
TDD 사이클 (0) | 2024.09.16 |
---|---|
Test Smell 처리 방법 (0) | 2024.09.09 |
Mock과 Stub의 차이 (0) | 2024.09.09 |
좋은 테스트의 요건 - RIGHT BICEP (0) | 2024.08.31 |
좋은 테스트의 요건 - FIRST (0) | 2024.08.31 |