#27 stock: race condition solution 1 - java syncronized

This commit is contained in:
haerong22
2022-12-20 22:35:43 +09:00
parent a5ba98db4b
commit 68f33e2ec5
2 changed files with 45 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
package com.example.stock.service;
import com.example.stock.domain.Stock;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class StockProxyService {
private final StockService stockService;
public synchronized void decrease(Long id, Long quantity) {
stockService.decrease(id, quantity);
}
}

View File

@@ -20,6 +20,9 @@ class StockServiceTest {
@Autowired
private StockService stockService;
@Autowired
private StockProxyService stockProxyService;
@Autowired
private StockRepository stockRepository;
@@ -69,4 +72,29 @@ class StockServiceTest {
// 100 - (1 * 100) = 0
assertEquals(0L, stock.getQuantity());
}
@Test
public void 동시에_100개의_요청_Proxy() throws InterruptedException {
int threadCount = 100;
ExecutorService executorService = Executors.newFixedThreadPool(32);
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
executorService.submit(() -> {
try {
stockProxyService.decrease(1L, 1L);
} finally {
latch.countDown();
}
});
}
latch.await();
Stock stock = stockRepository.findById(1L).orElseThrow();
// 100 - (1 * 100) = 0
assertEquals(0L, stock.getQuantity());
}
}