ReentrantLock과 synchronized 비교
ReentrantLock의 기능(tryLock, lockInterruptibly, 공정성)을 synchronized 키워드와 비교합니다.
ReentrantLock과 synchronized 비교은(는) CoddyKit의 무료 Java Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Java Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
동기화 키워드
Java의 synchronized 키워드는 객체의 고유 잠금(모니터)을 사용해 상호 배제를 제공합니다. 간단하지만 시간 제한, 공정성, 인터럽트 가능성이 없습니다.
class Counter {
private int count = 0;
synchronized void increment() {
count++; // only one thread at a time
}
synchronized int get() { return count; }
}
Counter c = new Counter();
// Multiple threads can safely call increment()ReentrantLock 기초
ReentrantLock은 java.util.concurrent.locks에 있는 명시적 잠금입니다. synchronized와 동일한 상호 배제를 제공하면서도 더 세밀하게 제어할 수 있습니다. 잠금은 반드시 마무리 블록에서 직접 해제해야 합니다.
import java.util.concurrent.locks.*;
class SafeCounter {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock(); // always release in finally!
}
}
int get() {
lock.lock();
try { return count; }
finally { lock.unlock(); }
}
}tryLock: 블로킹 없는 획득
tryLock()은 블로킹 없이 잠금 획득을 시도합니다. 성공하면 true를 반환하고, 다른 스레드가 잠금을 보유하고 있으면 false를 반환합니다.
ReentrantLock lock = new ReentrantLock();
if (lock.tryLock()) {
try {
System.out.println("Got the lock, doing work");
} finally {
lock.unlock();
}
} else {
System.out.println("Lock busy, skipping or retrying");
}tryLock과 시간 제한
지정된 시간 동안 잠금 획득을 기다립니다:
try {
if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
try {
// work with protected resource
System.out.println("Acquired within 500ms");
} finally {
lock.unlock();
}
} else {
System.out.println("Timed out waiting for lock");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}lockInterruptibly
lockInterruptibly()는 스레드가 인터럽트되지 않는 한 잠금을 획득합니다. 잠금을 기다리는 동안 취소할 수 있는 작업에 유용합니다:
try {
lock.lockInterruptibly(); // throws InterruptedException if interrupted
try {
// do work
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
System.out.println("Interrupted while waiting for lock");
Thread.currentThread().interrupt();
}재진입성
synchronized와 ReentrantLock은 모두 재진입성을 지원합니다. 이미 잠금을 보유한 스레드는 교착 상태를 일으키지 않고 잠금을 다시 획득할 수 있습니다:
synchronized void outer() {
System.out.println("outer");
inner(); // same thread re-enters — OK
}
synchronized void inner() {
System.out.println("inner"); // same lock, same thread
}
// ReentrantLock:
ReentrantLock lock = new ReentrantLock();
lock.lock();
lock.lock(); // acquire again — hold count = 2
lock.unlock(); // hold count = 1
lock.unlock(); // hold count = 0, lock released공정성 정책
공정한 ReentrantLock을 만들어 FIFO 순서로 접근을 허용합니다. 처리량은 낮아지지만 스레드 기아를 방지할 수 있습니다:
// Unfair (default): no ordering guarantee, better throughput
ReentrantLock unfair = new ReentrantLock();
// Fair: threads acquire in arrival order
ReentrantLock fair = new ReentrantLock(true);
System.out.println(fair.isFair()); // true조건 변수
ReentrantLock은 Condition 객체를 제공합니다. wait()/notify()보다 유연합니다:
ReentrantLock lock2 = new ReentrantLock();
Condition notEmpty = lock2.newCondition();
Queue<String> queue = new LinkedList<>();
// Producer
lock2.lock();
try {
queue.offer("item");
notEmpty.signal(); // wake one waiting thread
} finally { lock2.unlock(); }
// Consumer
lock2.lock();
try {
while (queue.isEmpty()) notEmpty.await(); // wait & release lock
System.out.println(queue.poll());
} finally { lock2.unlock(); }ReentrantLock과 동기화 중 무엇을 사용할까
다음과 같은 경우 동기화를 사용합니다:
- 간단한 상호 배제가 필요할 때
- 시간 제한, 공정성 또는 인터럽트 가능성이 필요하지 않을 때
다음과 같은 경우 ReentrantLock을 사용합니다:
- tryLock() 또는 시간 제한이 있는 tryLock이 필요할 때
- lockInterruptibly()가 필요할 때
- 공정한 순서가 필요할 때
- 여러 조건 변수가 필요할 때
잠금 횟수 및 모니터링
ReentrantLock은 진단 메서드를 제공합니다:
ReentrantLock lock3 = new ReentrantLock();
lock3.lock();
lock3.lock(); // reentrant — hold count 2
System.out.println(lock3.getHoldCount()); // 2
System.out.println(lock3.isHeldByCurrentThread()); // true
System.out.println(lock3.isLocked()); // true
System.out.println(lock3.getQueueLength()); // 0 (no waiting threads)
lock3.unlock();
lock3.unlock(); // fully released흔한 실수: 잠그지 않고 잠금 해제하기
현재 스레드가 잠금을 보유하지 않은 상태에서 unlock()을 호출하면 IllegalMonitorStateException이 발생합니다. 항상 lock/unlock을 쌍으로 사용하거나 try-finally를 사용합니다:
ReentrantLock lock4 = new ReentrantLock();
try {
// If lock() is never called (e.g., skipped by exception before this line)
lock4.unlock(); // throws IllegalMonitorStateException
} catch (IllegalMonitorStateException e) {
System.out.println("Must lock before unlock!");
}빠른 확인
잠금을 사용할 수 없을 때 블로킹하지 않고 즉시 반환하면서 잠금 획득을 시도할 수 있게 하는 ReentrantLock 메서드는 무엇입니까?
다시 보기: ReentrantLock과 동기화
핵심 정리:
- 둘 다 상호 배제와 재진입성을 제공합니다
- ReentrantLock은 tryLock, lockInterruptibly, 공정성, 조건 변수를 추가로 제공합니다
- 항상 마무리 블록에서 해제합니다
- synchronized는 더 간단하므로 기능이 충분할 때 우선 사용합니다
- 시간 제한, 인터럽트 가능성, 여러 조건이 필요한 고급 상황에서는 ReentrantLock을 사용합니다
자주 묻는 질문
“ReentrantLock과 synchronized 비교” 강의는 무료인가요?
네 — “ReentrantLock과 synchronized 비교” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Java Academy 강의 전체를 잠금 해제할 수 있습니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“ReentrantLock과 synchronized 비교”에서 뭘 배우나요?
ReentrantLock의 기능(tryLock, lockInterruptibly, 공정성)을 synchronized 키워드와 비교합니다. 브라우저에서 직접 실행하는 실습 코드로 Java Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Java Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Java Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“ReentrantLock과 synchronized 비교” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Java Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Java Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- ReentrantLock과 synchronized 비교
- 리더-라이터 상황을 위한 ReadWriteLock
- 원자적 변수: 잠금 없는 업데이트
- StampedLock과 낙관적 읽기