실습
💡synchronized
https://annovation.tistory.com/509
동시성 이슈 해결방법[2] - synchronized
synchronized로 동시성 이슈를 해결하지 못하는 이유와 @Transactional과의 충돌!
velog.io
💡Reentrant Lock
- 기본 사용법
private final ReentrantLock lock = new ReentrantLock();
public void method() {
lock.lock();
try {
// 비즈니스 로직
} finally {
lock.unlock();
}
}
- HubEleven 프로젝트 적용 실습
@Service
@RequiredArgsConstructor
public class StockServiceImpl implements StockService {
private final StockRepository stockRepository;
private final ProductRepository productRepository;
private final ReentrantLock lock = new ReentrantLock();
... (생략) ...
@Override
@Transactional
public StockResult decreaseStock(StockRequests.Decrease request) {
lock.lock();
try {
Product product = getProductOrThrow(request.productId());
Stock stock = getStockOrThrow(request.productId());
stock.decreaseQuantity(request.quantity());
return StockResult.from(stock, product.getName());
} finally {
lock.unlock();
}
}
}
✅ 한계 : MSA 와 같은 멀티 서버에서는 무용지물
멀티 서버 구성 예시
Server A → JVM A → Heap A → Object A(모니터 A)
Server B → JVM B → Heap B → Object B(모니터 B)
- Server A에서 synchronized/ReentrantLock으로 임계영역을 막아도
- Server B에서는 완전히 별개의 락이라 동시에 들어올 수 있음
참고 자료
1) Oracle Docs : ReentrantLock
https://docs.oracle.com/javase/17/docs/api/java.base/java/util/concurrent/locks/ReentrantLock.html
Overview (Java SE 17 & JDK 17)
This document is divided into two sections: Java SE The Java Platform, Standard Edition (Java SE) APIs define the core Java platform for general-purpose computing. These APIs are in modules whose names start with java. JDK The Java Development Kit (JDK) AP
docs.oracle.com
'Projects > HubEleven' 카테고리의 다른 글
| [동시성 처리] Trouble Shooting : 멀티스레드 재고 감소 통합 테스트 코드 Eureka Server Connection refused (0) | 2026.02.16 |
|---|---|
| [동시성 처리] JVM 락 : synchronized VS Reentrant Lock (실습중..) (0) | 2026.02.14 |
| [동시성 처리] Trouble Shooting : 테스트 코드 .env 환경 변수 적용 (0) | 2026.02.13 |
| [동시성 처리] Trouble Shooting : 테스트 코드 Config Client 오류 (0) | 2026.02.06 |
| [동시성 처리] 동시성 문제 (Race Condition) 해결 방법 3가지 관점 (실습중..) (0) | 2026.02.05 |