프로그래밍 언어/Kotlin
kotlin/java latch await not work 문제 troubleshooting
65살까지 코딩
2023. 7. 10. 22:21
728x90
반응형
동시성 문제에 대한 테스트를 위해
100개의 스레드에서 서비스에 접근하는 테스트를 하는 도중
latch.await을 했음에도 불구하고 계속해서 thread들이 끝나지도 않았는데, 테스트가 끝나는 문제가 있었다.
코드를 자세히 살펴보면 문제가 보이나,
맞다고 생각하고 대충보면 문제가 보이지 않는다... 이것 때문에 대략 1시간은 뻘짓을 한 것 같다..
@Test
fun decrease_concurrent() {
val threadCount = 100;
val executorService = Executors.newFixedThreadPool(threadCount)
val latch = CountDownLatch(threadCount);
for (i in 1..threadCount){
kotlin.runCatching {
executorService.submit {
stockService.decrease(stockId, 1)
}
}.also{
latch.countDown()
}
}
latch.await()
val stock = stockRepository.findById(stockId).get()
Assertions.assertThat(stock.quantity).isEqualTo(0L)
}
}
문제를 살펴보면 runCatching의 범위가 잘못 설정된 것이다.
executorService.submit은 thread를 시작시키는 것인데,
thread를 시작만 해놓고 latch.countDown()을 하니 모든 thread가 끝나기도전에 테스트가 끝나버리는 것이다.
따라서 해당 runCatching을 다음과 같이 바꿔주었다.
@Test
fun decrease_concurrent() {
val threadCount = 100;
val executorService = Executors.newFixedThreadPool(threadCount)
val latch = CountDownLatch(threadCount);
for (i in 1..threadCount) {
executorService.submit {
kotlin.runCatching {
stockService.decrease(stockId, 1)
}.also {
latch.countDown()
}
}
}
latch.await()
val stock = stockRepository.findById(stockId).get()
Assertions.assertThat(stock.quantity).isEqualTo(0L)
}
문제 해결 완료..
728x90
반응형