단일 스레드 환경
💡decreaseStock
@SpringBootTest
class StockApplicationTests {
@Autowired
private StockService stockService;
@Autowired
private StockRepository stockRepository;
// 테스트 전에 데이터베이스에 재고가 있어야 하므로 데이터 생성
@BeforeEach
public void before(){
stockRepository.saveAndFlush(new Stock(1L,100L));
}
// 테스트 후 데이터 삭제
@AfterEach
public void after(){
stockRepository.deleteAll();
}
@Test
public void 재고감소() {
stockService.decrease(1L, 1L);
Stock stock = stockRepository.findById(1L).orElseThrow();
assertEquals(99, stock.getQuantity());
}
}
멀티 스레드 환경
💡decreaseStock_when100ConcurrentRequests_thenSuccess
@Test
public void 동시에_100개의_요청() throws InterruptedException {
// 100개의 요청을 보낼 것임
int threadCount = 100;
// 멀티 스레드를 이용하기 위해 ExecutorService 사용 - (비동기로 실행하는 작업을 단순화하여 사용하게 하는 자바 api)
ExecutorService executorService = Executors.newFixedThreadPool(32);
CountDownLatch latch = new CountDownLatch(threadCount);
/*
1OO개의 요청이 모두 끝날때까지 기다려야 하므로 CountDownLatch 사용
CountDownLatch는 다른 스레드에서 수행죽인 작업이 완료될 때까지 대기할 수 있도록 도와주는 클래스 */
for(int i=0; i< threadCount; i++){
executorService.submit(()->{
try{
stockService.decrease(1L, 1L);
}finally {
latch.countDown();
}
});
}
latch.await();
Stock stock = stockRepository.findById(1L).orElseThrow();
// 100 - (1*00) = 0 : 예상 값
assertEquals(0, stock.getQuantity());
}
💡save() VS saveAndFlush() 차이
- save() 1
- 엔티티를 저장하거나 병합하지만 즉시 DB에 반영(flush)되지 않을 수 있다.
- 영속성 컨텍스트에 저장되어 트랜잭션 커밋 또는 필요시 flush 시 DB에 반영된다.
- saveAndFlush() 2
- save() 동작(영속화 또는 병합) 이후에, flush()가 호출되어 즉시 영속성 컨텍스트의 변경사항이 DB에 반영(동기화)된다.
- 트랜잭션 커밋을 기다리지 않고도 DB 반영이 필요한 경우 사용된다.
💡throws InterruptedException 하는 이유
참고 자료
1) https://dev-rosiepoise.tistory.com/129
[재고시스템으로 알아보는 동시성 이슈 해결방법] #2 재고감소 로직 작성 및 테스트
들어가기 전 ..1. 이전 게시글과 이어지는 게시글이므로 프로젝트 환경 및 세팅은 아래 링크에서 확인해주세요!2. 전체 코드는 아래의 Git에서 확인 가능합니다!참고하면 좋을 이전 글 [재고시스
dev-rosiepoise.tistory.com
2) https://dodop-blog.tistory.com/463
인프런) 재고시스템으로 알아보는 동시성 이슈 해결 (1)
동시성 이슈 해결을 위한 인프런 강의를 듣고 실습해보았다. https://www.inflearn.com/course/%EB%8F%99%EC%8B%9C%EC%84%B1%EC%9D%B4%EC%8A%88-%EC%9E%AC%EA%B3%A0%EC%8B%9C%EC%8A%A4%ED%85%9C/dashboard 재고시스템으로 알아보는 동
dodop-blog.tistory.com
3) https://velog.io/@kiteof_park/SpringBoot-동시성-이슈-해결방법1
동시성 이슈 해결방법[1] - 재고 감소 로직 작성
재고 감소 로직의 문제점과 Race Condition
velog.io
주석
'Projects > HubEleven' 카테고리의 다른 글
| [리팩토링] Stock 도메인 리팩토링 (2) (0) | 2025.12.27 |
|---|---|
| [리팩토링] Stock 도메인 리팩토링 (1) (0) | 2025.12.18 |
| [리팩토링] 서비스 코드 주석 제거, 메서드명 변경 (0) | 2025.12.17 |
| [동시성 처리] 재고 감소 통합 테스트 코드 2 (MSA 환경에서 코드 공유하기) (0) | 2025.12.11 |
| [동시성 처리] 실제 DB와 동일한 환경에서 테스트하기 (0) | 2025.12.09 |