• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

비관적 락 적용을 해도 동시성 테스트 시 실패합니다...

23.12.17 02:50 작성 조회수 258

0

StockRepository

public interface StockRepository extends JpaRepository<Stock, Long> {

    @Lock(value = LockModeType.PESSIMISTIC_WRITE)
    @Query("select s from Stock s where s.id = :id")
    Stock findByIdWithPessimisticLock(@Param("id") Long id);

}

StockService

@Service
@RequiredArgsConstructor
public class StockService {

    private final StockRepository stockRepository;

    @Transactional
    public Long decrease(Long id, Long quantity) {
        Stock stock = stockRepository.findByIdWithPessimisticLock(id);
        stock.decrease(quantity);
        stockRepository.saveAndFlush(stock);

        return stock.getQuantity();
    }
}

StockServiceTest

@SpringBootTest
class PessimisticLockStockServiceTest {

    @Autowired
    private StockService service;

    @Autowired
    private StockRepository stockRepository;

    @BeforeEach
    public void before() {
        stockRepository.saveAndFlush(new Stock(1L, 100L));
    }

    @AfterEach
    public void after() {
        stockRepository.deleteAll();
    }

    @Test
    @DisplayName("비관적 락을 사용해 재고 감소 동시성 요청이 완료된다.")
    void decrease() throws InterruptedException {
        // given
        int threadCnt = 100;
        ExecutorService executorService = Executors.newFixedThreadPool(32);
        CountDownLatch latch = new CountDownLatch(threadCnt);

        // when
        for (int i = 0; i < threadCnt; i++) {
            executorService.submit(() -> {
                try {
                    service.decrease(1L, 1L);
                } finally {
                    latch.countDown();
                }
            });
        }
        latch.await();

        // then
        Stock stock = stockRepository.findById(1L).orElseThrow();
        assertThat(stock.getQuantity()).isZero();
    }

}

해당 테스트를 돌리면 실패하고 순차적으로 재고가 감소되지 않고 수정 손실이 발생합니다. 아무리 찾아봐도 코드는 제대로 짠 것 같은데 무엇이 잘못 되었을까요??

답변 1

답변을 작성해보세요.

0

김앙두님 안녕하세요
문제가 발생되는 소스를 깃헙에 올려주신 후 깃헙주소를 공유해주실 수 있으실까요 ?

김앙두님의 프로필

김앙두

질문자

2023.12.18

앗 해결했습니다 ! application.yml 파일 설정을 잘못 해놔서 그랬네요 ㅠ