#27 stock: race condition solution 1 - java syncronized
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user