Projects/HubEleven

[동시성 처리] synchronized vs Reentrant Lock - 실습

annovation 2026. 2. 15. 22:50

실습

💡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