작성
·
392
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();
}
}
해당 테스트를 돌리면 실패하고 순차적으로 재고가 감소되지 않고 수정 손실이 발생합니다. 아무리 찾아봐도 코드는 제대로 짠 것 같은데 무엇이 잘못 되었을까요??
앗 해결했습니다 ! application.yml 파일 설정을 잘못 해놔서 그랬네요 ㅠ