스레드가 메모리를 어떻게 공유하는지, 경쟁 조건이 왜 생기는지, synchronized/volatile/Atomic/Lock 이 각각 무엇을 보장하는지 이해하고, ExecutorService 와 JDK 21 가상 스레드로 실무 병렬 처리를 안전하게 작성할 수 있게 됩니다.
웹 서버는 요청 하나마다 스레드 하나를 배정합니다. 톰캣 기본 설정은 200개 스레드가 동시에 같은 @Service 빈, 같은 캐시 Map, 같은 커넥션 풀을 건드립니다. "내 코드는 싱글 스레드로 테스트했는데 운영에서만 이상한 값이 나온다"는 문제의 90% 는 이 레슨에서 다루는 경쟁 조건(race condition)입니다. 재현이 안 되고 로그도 없기 때문에 원리를 모르면 며칠을 낭비합니다.
또한 성능 문제의 해결책도 멀티스레드입니다. 외부 API 10개를 순차 호출하면 10초, 병렬로 호출하면 1초입니다. 대용량 파일 100개를 파싱하는 배치, 이미지 리사이징, 대량 이메일 발송 — 모두 ExecutorService 나 가상 스레드로 처리합니다. 하지만 스레드를 잘못 쓰면 데드락으로 서버가 멈추거나, 스레드 풀 고갈로 모든 요청이 타임아웃됩니다.
JDK 21 의 가상 스레드(virtual thread)는 이 분야의 판을 바꿨습니다. 수백만 개의 스레드를 만들 수 있게 되면서 "스레드 풀 크기 튜닝"이라는 오래된 고민이 상당 부분 사라졌습니다. 하지만 가상 스레드도 공유 메모리 문제는 그대로 안고 있으므로, 이 레슨의 원리는 여전히 필수입니다.
| 프로세스(Process) | 스레드(Thread) | |
|---|---|---|
| 정의 | 실행 중인 프로그램. OS 가 자원(메모리, 파일 핸들)을 배정하는 단위 | 프로세스 안에서 실행되는 흐름. CPU 스케줄링 단위 |
| 메모리 | 독립된 주소 공간. 다른 프로세스 메모리 접근 불가 | 같은 프로세스의 힙을 공유. 스택만 각자 소유 |
| 생성 비용 | 큼 (주소 공간 복제) | 작음 (스택 하나 할당) |
| 통신 | IPC (파이프, 소켓, 공유 메모리) 필요 | 그냥 같은 변수를 읽고 쓰면 됨 — 그래서 위험 |
| 하나가 죽으면 | 다른 프로세스 무관 | 프로세스 전체(JVM)가 영향받을 수 있음 |
JVM 은 하나의 프로세스이고, 그 안에서 여러 스레드가 돕니다. main 도 스레드이고, GC 스레드, JIT 컴파일러 스레드가 백그라운드에서 함께 돕니다.
┌──────────────────────── JVM 프로세스 ────────────────────────┐
│ │
│ Thread-1 스택 Thread-2 스택 main 스택 │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ 지역변수 i │ │ 지역변수 i │ │ 지역변수 │ │
│ │ 참조 acc ─┼──┐ │ 참조 acc ─┼──┐ │ ... │ │
│ └──────────┘ │ └──────────┘ │ └──────────┘ │
│ │ │ │
│ ┌─────────────▼───────────────────▼──────── 힙(Heap) ──────┐ │
│ │ BankAccount 객체 { balance = 1000 } ← 모두가 공유 │ │
│ │ String 상수, 배열, 컬렉션 ... │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘핵심 판단 기준: "이 데이터를 두 스레드 이상이 동시에 접근하는가? 그중 하나라도 쓰기(write)를 하는가?" 둘 다 예 → 동기화 필요.
// 방법 1: Thread 상속
class Worker extends Thread { public void run() { ... } }
new Worker().start();
// 방법 2: Runnable 구현 (권장)
Runnable task = () -> { ... };
new Thread(task).start();Runnable 을 권장하는 이유:
| 이유 | 설명 |
|---|---|
| 단일 상속 제약 | 자바는 클래스 하나만 상속 가능. Thread 를 상속하면 다른 클래스를 상속할 수 없음 |
| 관심사 분리 | 무엇을(작업) 과 어떻게(스레드) 를 분리. 같은 작업을 어떤 실행기에도 넘김 |
| 람다 사용 | Runnable 은 함수형 인터페이스라 람다로 간결하게 작성 |
| 재사용 | 하나의 Runnable 을 여러 스레드가 공유 실행 가능 |
start() 와 run() 의 차이: run() 을 직접 호출하면 현재 스레드에서 그냥 메서드가 실행됩니다(새 스레드 없음). start() 가 OS 에 새 스레드를 요청하고, 그 스레드가 run() 을 호출합니다.
start()
NEW ───────────────────────► RUNNABLE ◄──────────────────┐
│ ▲ │
synchronized 락 대기 │ │ 락 획득 │ notify() / 시간 만료 /
▼ │ │ join 대상 종료
BLOCKED │
│ │
wait() / join() / park() │ │
────────────────────────────► WAITING ───────────────────┤
│
sleep(ms) / wait(ms) / join(ms) │
────────────────────────────► TIMED_WAITING ─────────────┘
run() 종료 / 예외 ──────────► TERMINATED| 상태 | 의미 |
|---|---|
| NEW | new Thread() 만 함. 아직 start() 전 |
| RUNNABLE | 실행 중이거나 CPU 를 기다리는 중(OS 스케줄러 대기 포함) |
| BLOCKED | synchronized 진입을 위해 모니터 락을 기다리는 중 |
| WAITING | wait(), join(), LockSupport.park() 로 무기한 대기 |
| TIMED_WAITING | sleep(ms), wait(ms) 등 시간 제한 대기 |
| TERMINATED | run() 이 끝남. 다시 start() 불가 |
운영에서 스레드 덤프(jstack)를 뜨면 이 상태들이 보입니다. BLOCKED 가 많으면 락 경합, WAITING 이 많으면 외부 I/O 대기나 데드락을 의심합니다.
count++ 는 왜 위험한가count++ 는 한 줄이지만 CPU 입장에서는 세 단계입니다.
1. LOAD : 메모리(힙)의 count 값을 CPU 레지스터로 읽는다 (읽기)
2. ADD : 레지스터 값에 1 을 더한다 (계산)
3. STORE : 레지스터 값을 메모리 count 에 쓴다 (쓰기)바이트코드로도 getfield → iconst_1 → iadd → putfield 네 명령입니다. 두 스레드가 이 사이에 끼어들면:
| 시각 | Thread-A | Thread-B | count |
|---|---|---|---|
| t1 | LOAD (0) | 0 | |
| t2 | LOAD (0) | 0 | |
| t3 | ADD → 1 | 0 | |
| t4 | ADD → 1 | 0 | |
| t5 | STORE 1 | 1 | |
| t6 | STORE 1 | 1 (2 여야 함) |
두 번 증가했는데 결과는 1 — 갱신 손실(lost update) 입니다. 이렇게 "여러 스레드의 실행 순서(interleaving, 끼어들기)에 따라 결과가 달라지는 상황"을 경쟁 조건이라 합니다. 발생 조건은 (1) 공유 상태 (2) 최소 하나의 쓰기 (3) 원자적이지 않은 연산 — 이 세 가지의 결합입니다.
해결 방향은 세 가지뿐입니다.
AtomicInteger, CASsynchronized, Lock 으로 한 번에 한 스레드만 진입synchronized 는 모니터 락(monitor lock, 또는 intrinsic lock) 을 사용합니다. 자바의 모든 객체는 자기만의 모니터를 하나씩 갖고 있습니다. 어떤 스레드가 그 모니터를 잡으면(acquire), 다른 스레드는 같은 모니터를 필요로 하는 코드에 들어올 수 없고 BLOCKED 상태로 기다립니다.
// 1) 메서드 동기화: 락 = this (static 이면 락 = Counter.class)
public synchronized void increment() { count++; }
// 2) 블록 동기화: 락 객체를 명시. 임계 영역(critical section)을 최소화할 수 있음
private final Object lock = new Object();
public void increment() {
// 락 없이 할 수 있는 일은 밖에서
synchronized (lock) { count++; } // 꼭 필요한 부분만 잠금
}| 방식 | 락 대상 | 특징 |
|---|---|---|
synchronized 인스턴스 메서드 |
this |
간단하지만 외부에서 this 로 락을 잡을 수 있어 통제 불가 |
synchronized static 메서드 |
Class 객체 |
모든 인스턴스가 하나의 락을 공유 |
synchronized (obj) 블록 |
obj |
락 범위 최소화 가능. 전용 private final Object lock 권장 |
재진입(reentrancy): 같은 스레드가 이미 잡은 락을 다시 요청하면 바로 통과합니다. 모니터는 "소유 스레드 + 재진입 횟수"를 기억하고, 카운트가 0 이 될 때 해제됩니다. 그래서 synchronized 메서드 안에서 같은 객체의 다른 synchronized 메서드를 호출해도 데드락이 나지 않습니다.
synchronized 가 보장하는 두 가지:
원자성과 별개로 가시성 문제가 있습니다. 현대 CPU 는 코어마다 캐시(L1/L2)를 갖고, 메모리 대신 캐시에서 읽고 씁니다. JIT 컴파일러도 "이 변수는 루프 안에서 안 바뀌네"라고 판단하면 읽기를 레지스터로 끌어올립니다(hoisting).
private boolean running = true; // volatile 없음
// Thread-A
while (running) { /* work */ } // JIT: running 을 한 번만 읽고 레지스터에 캐시 → 무한 루프 가능
// Thread-B
running = false; // 메인 메모리엔 썼지만 A 의 캐시/레지스터는 그대로volatile 은 "이 변수는 항상 메인 메모리에서 읽고 메인 메모리에 써라, 재배치(reordering)하지 마라"는 지시입니다.
volatile |
synchronized |
|
|---|---|---|
| 가시성 | O | O |
| 원자성 | X (count++ 는 여전히 위험) |
O |
| 블로킹 | 없음 | 있음 (락 대기) |
| 적합한 경우 | 플래그(on/off), 한 스레드만 쓰고 여럿이 읽는 설정 값 | 읽고-계산-쓰기 복합 연산 |
volatile int count; count++ 는 여전히 경쟁 조건입니다. volatile 은 읽기와 쓰기 각각을 메인 메모리와 동기화할 뿐, 읽기-계산-쓰기 세 단계를 하나로 묶어주지 않습니다.
자바 메모리 모델(JMM)은 "어떤 쓰기가 어떤 읽기에 보이는가"를 happens-before 관계로 정의합니다. A happens-before B 이면, A 의 결과가 B 에 보장되어 보입니다. 주요 규칙:
| 규칙 | 내용 |
|---|---|
| 프로그램 순서 | 한 스레드 안에서 앞 문장은 뒤 문장보다 먼저 |
| 모니터 락 | unlock 은 이후의 같은 락 lock 보다 먼저 |
| volatile | volatile 쓰기는 이후의 같은 변수 volatile 읽기보다 먼저 |
| 스레드 시작 | t.start() 는 t 안의 모든 동작보다 먼저 |
| 스레드 종료 | t 의 모든 동작은 t.join() 리턴보다 먼저 |
| 추이성 | A→B, B→C 이면 A→C |
실무 함의: Thread.join() 후에 결과를 읽으면 동기화 없이도 안전하게 보입니다. ExecutorService.submit() 전의 동작은 작업 안에서 보이고, Future.get() 후에는 작업의 결과가 보입니다. 이 규칙 덕분에 스레드 풀에 결과 객체를 넘겨받을 때 별도의 volatile 이 필요 없습니다.
AtomicInteger, AtomicLong, AtomicReference 는 락 없이 원자적 갱신을 제공합니다. 내부는 CPU 의 CAS 명령(x86 의 cmpxchg)입니다.
CAS(주소, 기대값, 새값):
if (메모리[주소] == 기대값) { 메모리[주소] = 새값; return true; }
else return false;
← 이 비교-교체가 하드웨어 수준에서 원자적으로 실행됨incrementAndGet() 의 실제 동작:
int current;
do {
current = get(); // 현재 값 읽기
} while (!compareAndSet(current, current + 1)); // 그 사이 안 바뀌었으면 교체, 바뀌었으면 재시도락을 잡지 않으므로 BLOCKED 가 없고(non-blocking), 경합이 적을 때 synchronized 보다 훨씬 빠릅니다. 경합이 극심하면 재시도가 반복되어 오히려 느려질 수 있는데, 그럴 때는 LongAdder(내부적으로 셀을 분산)를 씁니다.
java.util.concurrent.locks.ReentrantLock 은 synchronized 와 같은 상호 배제를 제공하면서 추가 기능이 있습니다.
| 기능 | synchronized |
ReentrantLock |
|---|---|---|
| 타임아웃 시도 | X | tryLock(1, SECONDS) |
| 인터럽트 가능 대기 | X | lockInterruptibly() |
| 공정성(fairness, 대기 순서 보장) | X | new ReentrantLock(true) |
| 조건 변수 여러 개 | wait/notify 하나 |
newCondition() 여러 개 |
| 락 해제 | 블록 끝에서 자동 | finally 에서 반드시 unlock() |
private final ReentrantLock lock = new ReentrantLock();
public void transfer() {
lock.lock();
try { /* 임계 영역 */ }
finally { lock.unlock(); } // 예외가 나도 반드시 해제
}단순한 경우엔 synchronized 가 더 안전(unlock 깜빡 못 함)하고, 타임아웃/공정성이 필요할 때만 ReentrantLock 을 씁니다.
두 스레드가 서로가 가진 락을 기다리며 영원히 멈추는 상태입니다.
Thread-A: lock(계좌1) → lock(계좌2) 대기 ─┐
│ 서로 기다림 → 영원히 정지
Thread-B: lock(계좌2) → lock(계좌1) 대기 ─┘데드락은 다음 4가지 조건이 모두 성립할 때만 발생합니다(Coffman 조건).
| 조건 | 의미 | 깨는 방법 |
|---|---|---|
| 상호 배제 | 자원을 한 번에 하나만 사용 | 락 자체를 없앰 (불변 객체, Atomic) |
| 점유와 대기 | 자원을 쥔 채 다른 자원을 기다림 | 필요한 락을 한꺼번에 획득, 또는 tryLock 실패 시 전부 해제 |
| 비선점 | 남의 자원을 뺏을 수 없음 | tryLock(timeout) 으로 포기 |
| 순환 대기 | A→B→A 원형 대기 | 락 순서 고정 (가장 실용적) |
실무 예방책 우선순위:
jstack 이 "Found one Java-level deadlock" 을 알려줌. ThreadMXBean.findDeadlockedThreads() 로 프로그램에서도 감지 가능.스레드를 매번 만들면 비용이 크고(OS 스레드 생성, 1MB 스택) 개수 제한도 없어 위험합니다. 스레드 풀은 스레드를 미리 만들어 재사용합니다.
| 팩토리 | 동작 | 적합한 경우 |
|---|---|---|
newFixedThreadPool(n) |
정확히 n 개. 초과 작업은 무한 큐에 대기 | CPU 바운드, 동시성 상한 필요할 때 |
newCachedThreadPool() |
필요하면 계속 생성, 60초 놀면 제거. 큐 없음 | 짧은 작업 폭주. 무제한 생성 위험 |
newSingleThreadExecutor() |
1개. 순서 보장 | 순차 처리가 필요한 이벤트 |
newVirtualThreadPerTaskExecutor() (21) |
작업마다 가상 스레드 | I/O 바운드 대량 작업 |
newScheduledThreadPool(n) |
지연/주기 실행 | 스케줄러 |
newFixedThreadPool 의 큐가 무한(LinkedBlockingQueue)이라 작업이 쌓이면 OOM 이 날 수 있고, newCachedThreadPool 은 스레드가 무한히 늘 수 있습니다. 실무에서는 new ThreadPoolExecutor(core, max, keepAlive, unit, new ArrayBlockingQueue<>(cap), rejectionPolicy) 로 직접 상한을 정하는 것이 원칙입니다.
submit vs execute:
execute(Runnable) |
submit(Runnable/Callable) |
|
|---|---|---|
| 반환 | void |
Future<T> |
| 예외 | 스레드의 UncaughtExceptionHandler 로 → 콘솔에 찍히고 사라짐 |
Future 안에 저장. get() 할 때 ExecutionException 으로 나옴 |
| 함정 | get() 을 안 하면 예외가 조용히 사라짐 |
올바른 종료:
executor.shutdown(); // 새 작업 거부, 기존 작업은 완료
if (!executor.awaitTermination(30, TimeUnit.SECONDS)) { // 완료 대기
executor.shutdownNow(); // 시간 초과 시 강제 인터럽트
}shutdown() 을 안 하면 non-daemon 워커 스레드가 살아 있어 JVM 이 종료되지 않습니다. JDK 19+ 에서는 ExecutorService 가 AutoCloseable 이라 try-with-resources 가 close() 에서 shutdown + awaitTermination 을 해줍니다.
Future.get() 은 블로킹입니다. CompletableFuture 는 "완료되면 이걸 해라"를 체이닝합니다.
CompletableFuture<Order> orderF = CompletableFuture.supplyAsync(() -> fetchOrder(id), pool);
CompletableFuture<User> userF = CompletableFuture.supplyAsync(() -> fetchUser(id), pool);
CompletableFuture<String> result = orderF
.thenCombine(userF, (order, user) -> user.name() + ":" + order.amount()) // 둘 다 끝나면
.thenApply(String::toUpperCase) // 변환
.exceptionally(ex -> "FALLBACK"); // 실패 시
String s = result.join();| 메서드 | 역할 |
|---|---|
supplyAsync(Supplier, executor) |
비동기 시작. executor 생략 시 ForkJoinPool.commonPool() |
thenApply(f) |
결과 변환 (map) |
thenCompose(f) |
결과로 또 다른 CompletableFuture 실행 (flatMap) |
thenCombine(other, f) |
두 결과 합치기 |
allOf(...) / anyOf(...) |
여러 개 모두/하나 완료 대기 |
exceptionally(f) / handle(f) |
예외 처리 |
join() / get() |
블로킹 결과 획득 |
기존 스레드(플랫폼 스레드)는 OS 스레드와 1:1 이라 무겁습니다(생성 ~1ms, 스택 1MB, 수천 개가 한계). 가상 스레드는 JVM 이 관리하는 가벼운 스레드로, 소수의 OS 스레드(캐리어) 위에 수백만 개를 올릴 수 있습니다.
가상 스레드 100만 개 ──┐
├── 캐리어(플랫폼) 스레드 8개 (CPU 코어 수) ── OS
가상 스레드가 I/O 로 블로킹되면 → 캐리어에서 내려오고(unmount) 다른 가상 스레드가 올라감(mount)try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 100_000; i++) {
executor.submit(() -> { Thread.sleep(1000); return 1; }); // 10만 개가 1초 만에 끝남
}
} // close() 가 모든 작업 완료 대기| 플랫폼 스레드 | 가상 스레드 | |
|---|---|---|
| 매핑 | OS 스레드 1:1 | M:N (JVM 스케줄링) |
| 생성 비용 | 큼 | 매우 작음 (객체 하나) |
| 최대 개수 | 수천 | 수백만 |
| 블로킹 I/O | OS 스레드가 놀게 됨 | 캐리어를 양보 → 효율적 |
| 적합 | CPU 바운드 계산 | I/O 바운드 (HTTP 호출, DB, 파일) |
| 풀링 | 필수 | 하지 말 것 (작업마다 새로 만듦) |
언제 쓰나: 요청당 스레드 모델에서 I/O 대기가 대부분인 작업(외부 API 호출, DB 쿼리). CPU 계산은 어차피 코어 수만큼만 병렬이라 이득이 없습니다. 주의: synchronized 블록 안에서 블로킹하면 캐리어가 고정(pinned)되어 이점이 사라지므로(JDK 21 기준, 24에서 개선) ReentrantLock 을 쓰는 것이 좋습니다.
ThreadLocal<T> 은 "변수 하나인데 스레드마다 값이 다른" 저장소입니다. 스프링의 SecurityContextHolder, 트랜잭션 컨텍스트, SimpleDateFormat(스레드 안전하지 않음) 공유가 대표 용도입니다.
private static final ThreadLocal<String> REQUEST_ID = ThreadLocal.withInitial(() -> "none");
REQUEST_ID.set("req-42"); // 이 스레드에서만 보임
String id = REQUEST_ID.get();
REQUEST_ID.remove(); // 스레드 풀에서는 반드시 remove! 안 하면 다음 요청이 이전 값을 봄스레드 풀은 스레드를 재사용하므로 remove() 를 빼먹으면 다른 요청의 값이 새어나가는 보안 사고가 됩니다. 가상 스레드는 매번 새로 만들어지니 이 문제는 없지만 수백만 개에 ThreadLocal 을 쓰면 메모리가 부담이라 JDK 21 프리뷰 ScopedValue 가 대안으로 나왔습니다.
같은 count++ 를 (1) 무방비 (2) synchronized (3) AtomicInteger 로 각각 실행해 결과를 비교합니다.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class RaceConditionDemo {
static int unsafeCount = 0;
static int syncCount = 0;
static final AtomicInteger atomicCount = new AtomicInteger();
static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
int threads = 8, perThread = 100_000;
Runnable work = () -> {
for (int i = 0; i < perThread; i++) {
unsafeCount++; // 경쟁 조건
synchronized (lock) { syncCount++; } // 상호 배제
atomicCount.incrementAndGet(); // CAS
}
};
Thread[] ts = new Thread[threads];
for (int i = 0; i < threads; i++) { ts[i] = new Thread(work); ts[i].start(); }
for (Thread t : ts) t.join(); // join 후 읽기는 happens-before 로 안전
int expected = threads * perThread;
System.out.println("expected = " + expected);
System.out.println("unsafe = " + unsafeCount + (unsafeCount == expected ? "" : " <-- 갱신 손실"));
System.out.println("sync = " + syncCount);
System.out.println("atomic = " + atomicCount.get());
}
}
// 출력 (unsafe 값은 실행마다 다름):
// expected = 800000
// unsafe = 613482 <-- 갱신 손실
// sync = 800000
// atomic = 800000두 계좌 사이를 양방향으로 동시에 이체하면 락 순서가 엇갈려 데드락이 납니다. 계좌 ID 순으로 락을 잡아 순환 대기를 끊습니다.
import java.util.concurrent.*;
public class BankAccount {
private final int id;
private long balance;
BankAccount(int id, long balance) { this.id = id; this.balance = balance; }
long balance() { synchronized (this) { return balance; } }
static void transfer(BankAccount from, BankAccount to, long amount) {
// 순환 대기 차단: 항상 id 가 작은 계좌부터 잠근다
BankAccount first = from.id < to.id ? from : to;
BankAccount second = from.id < to.id ? to : from;
synchronized (first) {
synchronized (second) {
if (from.balance < amount) throw new IllegalStateException("잔액 부족");
from.balance -= amount;
to.balance += amount;
}
}
}
public static void main(String[] args) throws Exception {
BankAccount a = new BankAccount(1, 1_000_000);
BankAccount b = new BankAccount(2, 1_000_000);
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
for (int i = 0; i < 10_000; i++) {
pool.submit(() -> transfer(a, b, 10)); // a → b
pool.submit(() -> transfer(b, a, 10)); // b → a (역방향, 데드락 후보)
}
} // close(): shutdown + awaitTermination
System.out.println("a = " + a.balance() + ", b = " + b.balance());
System.out.println("total = " + (a.balance() + b.balance())); // 불변식: 합계 보존
}
}
// 출력:
// a = 1000000, b = 1000000
// total = 2000000일부러 락 순서를 엇갈리게 잡아 데드락을 만들고, ThreadMXBean 으로 감지한 뒤, tryLock 버전으로 같은 작업이 끝나는 것을 보여줍니다.
import java.lang.management.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;
public class DeadlockDemo {
public static void main(String[] args) throws Exception {
ReentrantLock l1 = new ReentrantLock(), l2 = new ReentrantLock();
// 1) 데드락 재현: 서로 반대 순서
Thread t1 = new Thread(() -> grabBoth(l1, l2), "T1");
Thread t2 = new Thread(() -> grabBoth(l2, l1), "T2");
t1.start(); t2.start();
t1.join(500); t2.join(500); // 타임아웃으로 안전 종료
long[] dead = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
System.out.println("deadlocked threads = " + (dead == null ? 0 : dead.length));
t1.interrupt(); t2.interrupt(); // lockInterruptibly 대기 중이므로 깨어남
t1.join(); t2.join();
// 2) tryLock: 못 잡으면 포기하고 재시도 → 데드락 없음
ReentrantLock a = new ReentrantLock(), b = new ReentrantLock();
Thread t3 = new Thread(() -> tryBoth(a, b), "T3");
Thread t4 = new Thread(() -> tryBoth(b, a), "T4");
t3.start(); t4.start(); t3.join(); t4.join();
System.out.println("tryLock version finished");
}
static void grabBoth(ReentrantLock first, ReentrantLock second) {
try {
first.lockInterruptibly();
try {
Thread.sleep(100); // 상대가 다른 락을 잡을 시간
second.lockInterruptibly(); // 여기서 영원히 대기 → 데드락
second.unlock();
} finally { first.unlock(); }
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted");
}
}
static void tryBoth(ReentrantLock first, ReentrantLock second) {
while (true) {
if (first.tryLock()) {
try {
if (second.tryLock()) {
try { return; } finally { second.unlock(); }
}
} finally { first.unlock(); } // 두 번째 실패 → 첫 번째도 놓고 재시도 (점유와 대기 깨기)
}
Thread.onSpinWait();
}
}
}
// 출력:
// deadlocked threads = 2
// T1 interrupted
// T2 interrupted
// tryLock version finished주문 이벤트를 생산자가 큐에 넣고 소비자 2개가 꺼내 처리합니다. BlockingQueue 가 락과 대기를 내부에서 처리하므로 wait/notify 를 직접 쓸 필요가 없습니다. 종료는 "독약(poison pill)" 방식입니다.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ProducerConsumer {
record OrderEvent(int id, long amount) {}
static final OrderEvent POISON = new OrderEvent(-1, 0);
public static void main(String[] args) throws InterruptedException {
BlockingQueue<OrderEvent> queue = new ArrayBlockingQueue<>(10); // 용량 10: 가득 차면 put 이 대기
AtomicInteger processed = new AtomicInteger();
int consumers = 2, total = 50;
Runnable consumer = () -> {
try {
while (true) {
OrderEvent e = queue.take(); // 비어 있으면 대기
if (e == POISON) break;
processed.incrementAndGet();
}
} catch (InterruptedException ex) { Thread.currentThread().interrupt(); }
};
Thread[] cs = new Thread[consumers];
for (int i = 0; i < consumers; i++) { cs[i] = new Thread(consumer, "consumer-" + i); cs[i].start(); }
for (int i = 1; i <= total; i++) queue.put(new OrderEvent(i, i * 100L)); // 생산
for (int i = 0; i < consumers; i++) queue.put(POISON); // 소비자 수만큼 독약
for (Thread c : cs) c.join();
System.out.println("processed = " + processed.get());
System.out.println("queue empty = " + queue.isEmpty());
}
}
// 출력:
// processed = 50
// queue empty = true파일 100개를 읽어 줄 수를 세는 작업을 submit + Future 로 처리하고, 같은 작업을 가상 스레드로 돌립니다. 실패 작업의 예외가 Future.get() 에서 나오는 것도 확인합니다.
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
public class ParallelFiles {
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("logs");
for (int i = 0; i < 100; i++)
Files.writeString(dir.resolve("app-" + i + ".log"), "line\n".repeat(i + 1));
long t0 = System.nanoTime();
long total = countLines(dir, Executors.newFixedThreadPool(8));
System.out.println("fixed pool total lines = " + total);
long total2 = countLines(dir, Executors.newVirtualThreadPerTaskExecutor());
System.out.println("virtual thread total lines = " + total2);
System.out.println("both done in < 1s: " + ((System.nanoTime() - t0) / 1_000_000_000 < 1));
}
static long countLines(Path dir, ExecutorService pool) throws Exception {
List<Future<Long>> futures = new ArrayList<>();
try (pool; var files = Files.list(dir)) {
for (Path p : files.toList())
futures.add(pool.submit(() -> { try (var s = Files.lines(p)) { return s.count(); } }));
}
long sum = 0;
for (Future<Long> f : futures) {
try { sum += f.get(); }
catch (ExecutionException e) { System.out.println("failed: " + e.getCause()); } // 작업 안 예외는 여기서
}
return sum;
}
}
// 출력:
// fixed pool total lines = 5050
// virtual thread total lines = 5050
// both done in < 1s: true3장의 예제를 "다른 동기화 도구로", "실무 조회 흐름에", "종료·실패 같은 엣지 케이스에", "성능 비교로" 바꿔 봅니다. 같은 문제를 여러 도구로 풀어 보면 "이 상황엔 무엇을 쓰는가"가 원리와 함께 손에 익습니다.
예제 1 은 "정확한가"만 봤습니다. 이번엔 같은 800만 번 증가를 네 가지 방식으로 돌려 시간 을 잽니다. 경합이 심한 단순 카운터에서는 CAS 재시도가 몰리는 AtomicLong 보다 셀을 분산하는 LongAdder 가 빠르고, ReentrantLock 은 synchronized 와 비슷합니다. "통계용 카운터는 LongAdder, 값을 읽어 판단해야 하면 AtomicLong, 복합 연산이면 락"이 선택 기준입니다.
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.LongSupplier;
public class CounterBenchmark {
static long syncCount; static final Object lock = new Object();
static final AtomicLong atomic = new AtomicLong();
static final LongAdder adder = new LongAdder();
static long lockCount; static final ReentrantLock rlock = new ReentrantLock();
// 같은 "증가" 작업을 4가지 동기화 방식으로 돌리고 시간을 잰다
static void bench(String name, Runnable inc, LongSupplier result, int threads, int perThread) throws InterruptedException {
long t0 = System.nanoTime();
Thread[] ts = new Thread[threads];
for (int i = 0; i < threads; i++) {
ts[i] = new Thread(() -> { for (int k = 0; k < perThread; k++) inc.run(); });
ts[i].start();
}
for (Thread t : ts) t.join();
System.out.printf("%-14s = %,d (%d ms)%n", name, result.getAsLong(), (System.nanoTime() - t0) / 1_000_000);
}
public static void main(String[] args) throws InterruptedException {
int threads = 8, per = 1_000_000;
bench("synchronized", () -> { synchronized (lock) { syncCount++; } }, () -> syncCount, threads, per);
bench("AtomicLong", atomic::incrementAndGet, atomic::get, threads, per);
bench("LongAdder", adder::increment, adder::sum, threads, per);
bench("ReentrantLock", () -> { rlock.lock(); try { lockCount++; } finally { rlock.unlock(); } }, () -> lockCount, threads, per);
}
}
// 출력 (ms 값은 CPU·코어 수·부하에 따라 다름. 합계는 항상 8,000,000):
// synchronized = 8,000,000 (1488 ms)
// AtomicLong = 8,000,000 (874 ms)
// LongAdder = 8,000,000 (515 ms)
// ReentrantLock = 8,000,000 (1344 ms)2.13 의 thenCombine 을 실무 흐름에 적용합니다. 순차 호출은 세 조회 시간의 합, 팬아웃은 최댓값 이 걸립니다. 재고 서비스만 죽었을 때 전체를 실패시키지 않고 exceptionally 로 그 조각만 대체값으로 채우는 것이 부분 실패 처리입니다. 응답 시간이 여러 외부 호출의 합으로 늘어나는 API 조합(BFF, 주문 상세 화면)에 이 패턴을 씁니다.
import java.util.concurrent.*;
public class OrderFanOut {
record Order(String id, long amount) {}
record User(String name, String grade) {}
record Stock(int qty) {}
static <T> T slow(long ms, T value) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
return value;
}
static Order fetchOrder(String id) { return slow(300, new Order(id, 45_000)); }
static User fetchUser(String id) { return slow(300, new User("kim", "VIP")); }
static Stock fetchStock(String id) {
if (id.endsWith("9")) throw new IllegalStateException("재고 서비스 다운");
return slow(300, new Stock(3));
}
// 세 조회를 동시에 시작하고, 재고 조회만 실패해도 나머지 결과는 살린다
static String summary(String orderId, ExecutorService pool) {
CompletableFuture<Order> orderF = CompletableFuture.supplyAsync(() -> fetchOrder(orderId), pool);
CompletableFuture<User> userF = CompletableFuture.supplyAsync(() -> fetchUser(orderId), pool);
CompletableFuture<Stock> stockF = CompletableFuture.supplyAsync(() -> fetchStock(orderId), pool)
.exceptionally(ex -> new Stock(-1)); // 부분 실패 → fallback
return orderF.thenCombine(userF, (o, u) -> u.name() + "(" + u.grade() + ") " + o.id() + " " + o.amount() + "원")
.thenCombine(stockF, (s, st) -> s + " 재고=" + (st.qty() < 0 ? "조회실패" : st.qty()))
.join();
}
public static void main(String[] args) {
try (ExecutorService pool = Executors.newFixedThreadPool(6)) {
long t0 = System.currentTimeMillis();
String seq = fetchUser("ORD-1").name() + " " + fetchOrder("ORD-1").amount() + " " + fetchStock("ORD-1").qty();
long seqMs = System.currentTimeMillis() - t0;
t0 = System.currentTimeMillis();
String par = summary("ORD-1", pool);
long parMs = System.currentTimeMillis() - t0;
System.out.println("순차: " + seq + " (~" + seqMs / 100 * 100 + "ms)");
System.out.println("병렬: " + par + " (~" + parMs / 100 * 100 + "ms)");
System.out.println("부분 실패: " + summary("ORD-9", pool));
}
}
}
// 출력 (시간은 환경에 따라 다름. 순차 ≈ 300ms × 3, 병렬 ≈ 300ms × 1 의 비율이 핵심. 아래는 부하가 높은 PC 의 실측):
// 순차: kim 45000 3 (~3800ms)
// 병렬: kim(VIP) ORD-1 45000원 재고=3 (~1200ms)
// 부분 실패: kim(VIP) ORD-9 45000원 재고=조회실패예제 4 의 소비자는 독약(poison pill)으로 끝냈습니다. 실무에서는 shutdownNow() 가 보내는 인터럽트 로 끝내는 경우가 더 많은데, 워커가 InterruptedException 을 삼키면 풀이 영원히 종료되지 않습니다.
올바른 워커는 (1) 루프 조건에서 플래그를 확인하고 (2) 예외를 받으면 Thread.currentThread().interrupt() 로 플래그를 복원한 뒤 빠져나옵니다. 잘못된 워커는 데몬 스레드로 만들어 JVM 종료만은 막지 않게 했습니다.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class GracefulShutdown {
static final AtomicInteger goodDone = new AtomicInteger(), badDone = new AtomicInteger();
// 올바른 워커: 인터럽트 플래그를 확인하고, 예외를 받으면 플래그를 복원한 뒤 빠져나온다
static Runnable goodWorker(BlockingQueue<Integer> q) {
return () -> {
try {
while (!Thread.currentThread().isInterrupted()) {
Integer job = q.poll(50, TimeUnit.MILLISECONDS); // 대기 중 인터럽트 → InterruptedException
if (job == null) continue;
Thread.sleep(5); // 처리 (블로킹 구간)
goodDone.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 플래그 복원: 호출자도 알 수 있게
}
System.out.println(Thread.currentThread().getName() + " 종료, interrupted=" + Thread.currentThread().isInterrupted());
};
}
// 잘못된 워커: InterruptedException 을 삼킨다 → shutdownNow 로도 멈추지 않는다
static Runnable badWorker(BlockingQueue<Integer> q) {
return () -> {
while (true) {
try {
Integer job = q.poll(50, TimeUnit.MILLISECONDS);
if (job != null) { Thread.sleep(5); badDone.incrementAndGet(); }
} catch (InterruptedException e) { /* 삼킴 */ }
}
};
}
public static void main(String[] args) throws Exception {
BlockingQueue<Integer> jobs = new LinkedBlockingQueue<>();
for (int i = 0; i < 10_000; i++) jobs.add(i);
ExecutorService good = Executors.newFixedThreadPool(2, Thread.ofPlatform().name("good-", 0).factory());
ExecutorService bad = Executors.newFixedThreadPool(1, Thread.ofPlatform().name("bad-", 0).daemon(true).factory());
good.submit(goodWorker(jobs)); good.submit(goodWorker(jobs));
bad.submit(badWorker(jobs));
Thread.sleep(200);
good.shutdownNow(); // 워커에 interrupt()
bad.shutdownNow();
System.out.println("good 풀 종료됨 = " + good.awaitTermination(1, TimeUnit.SECONDS));
System.out.println("bad 풀 종료됨 = " + bad.awaitTermination(300, TimeUnit.MILLISECONDS));
System.out.println("처리 건수 good=" + goodDone.get() + " bad=" + badDone.get());
} // bad 워커는 데몬 스레드라 JVM 종료를 막지 못한다. 데몬이 아니었다면 프로그램이 끝나지 않는다
}
// 출력 (good-0/good-1 줄의 순서와 처리 건수는 실행마다 다름):
// good-0 종료, interrupted=true
// good-1 종료, interrupted=true
// good 풀 종료됨 = true
// bad 풀 종료됨 = false
// 처리 건수 good=65 bad=14예제 1 은 join 으로만 기다렸습니다. 워커가 "동시에 출발"하고 "전원이 1단계를 끝낸 뒤" 병합해야 하는 배치에는 래치(출발 신호·완료 대기) 와 배리어(집합 지점 + 한 번만 실행되는 병합 액션) 가 맞습니다. 공유 배열에 쓰지 않고 워커별 부분합을 따로 두었다가 배리어 액션에서 합치므로 락이 하나도 없고, await() 이후 읽기는 happens-before 로 안전합니다.
import java.util.*;
import java.util.concurrent.*;
public class PhasedSettlement {
record Tx(int merchant, long amount) {}
public static void main(String[] args) throws Exception {
List<Tx> txs = new ArrayList<>();
Random rnd = new Random(42);
for (int i = 0; i < 100_000; i++) txs.add(new Tx(rnd.nextInt(5), rnd.nextInt(10_000)));
int workers = 4, merchants = 5;
long[][] partial = new long[workers][merchants]; // 워커별 부분합 (공유 쓰기 없음)
long[] total = new long[merchants];
CountDownLatch startGate = new CountDownLatch(1); // 모두 준비되면 동시에 출발
CyclicBarrier phase = new CyclicBarrier(workers, () -> { // 4명이 전부 도착하면 딱 한 번 실행
for (long[] p : partial) for (int m = 0; m < merchants; m++) total[m] += p[m];
System.out.println("phase 1 완료 → 병합 (barrier action, 한 번만 실행)");
});
CountDownLatch done = new CountDownLatch(workers);
for (int w = 0; w < workers; w++) {
int id = w;
new Thread(() -> {
try {
startGate.await();
for (int i = id; i < txs.size(); i += workers) // 파티션: i % workers == id
partial[id][txs.get(i).merchant()] += txs.get(i).amount();
phase.await(); // 전원 집합 후 병합
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
done.countDown();
}
}, "worker-" + id).start();
}
startGate.countDown();
done.await(); // await 이후 읽기는 happens-before 로 안전
for (int w = 0; w < workers; w++)
System.out.println("worker-" + w + " 부분합 " + Arrays.stream(partial[w]).sum());
System.out.println("가맹점별 합계 = " + Arrays.toString(total));
long expected = txs.stream().mapToLong(Tx::amount).sum();
System.out.println("검산: " + Arrays.stream(total).sum() + " == " + expected + " → " + (Arrays.stream(total).sum() == expected));
}
}
// 출력:
// phase 1 완료 → 병합 (barrier action, 한 번만 실행)
// worker-0 부분합 124875201
// worker-1 부분합 124983068
// worker-2 부분합 125854664
// worker-3 부분합 125886327
// 가맹점별 합계 = [100086159, 101104212, 99141529, 101151324, 100116036]
// 검산: 501599260 == 501599260 → true예제 5 는 두 방식의 결과가 같음을 보였고, 이번엔 시간 을 비교합니다. 50ms 대기 작업 1,000개를 16개 플랫폼 스레드로 돌리면 이론상 63 라운드 × 50ms ≈ 3초, 가상 스레드는 전부 동시에 대기하므로 ≈ 50ms 입니다. 일부 작업이 예외를 던져도 Future.get() 에서 하나씩 받아 성공·실패를 따로 모으므로 전체가 멈추지 않습니다. 외부 API 대량 호출, 알림 발송 배치가 이 형태입니다.
import java.util.*;
import java.util.concurrent.*;
public class VirtualVsPlatform {
static String call(int id) throws Exception {
Thread.sleep(50); // 외부 API 지연 (I/O 대기)
if (id % 250 == 0) throw new IllegalStateException("timeout id=" + id); // 일부 실패
return "ok-" + id;
}
record Outcome(int ok, List<String> failures, long ms) {}
static Outcome run(ExecutorService pool, int n) throws Exception {
long t0 = System.currentTimeMillis();
List<Future<String>> fs = new ArrayList<>();
try (pool) {
for (int i = 1; i <= n; i++) { int id = i; fs.add(pool.submit(() -> call(id))); }
} // close(): 전부 끝날 때까지 대기
int ok = 0;
List<String> failures = new ArrayList<>();
for (Future<String> f : fs) {
try { f.get(); ok++; }
catch (ExecutionException e) { failures.add(e.getCause().getMessage()); } // 실패는 모아서 보고
}
return new Outcome(ok, failures, System.currentTimeMillis() - t0);
}
public static void main(String[] args) throws Exception {
int n = 1000;
Outcome p = run(Executors.newFixedThreadPool(16), n);
Outcome v = run(Executors.newVirtualThreadPerTaskExecutor(), n);
System.out.printf("플랫폼 풀(16): 성공 %d, 실패 %d, %d ms%n", p.ok(), p.failures().size(), p.ms());
System.out.printf("가상 스레드 : 성공 %d, 실패 %d, %d ms%n", v.ok(), v.failures().size(), v.ms());
System.out.println("실패 목록: " + v.failures());
System.out.println("이론값: 플랫폼 = 1000/16 × 50ms ≈ 3150ms, 가상 ≈ 50ms");
}
}
// 출력 (ms 는 환경에 따라 다름. 부하가 높은 PC 의 실측이며, 한가한 PC 에서는 이론값에 가까워짐):
// 플랫폼 풀(16): 성공 996, 실패 4, 5696 ms
// 가상 스레드 : 성공 996, 실패 4, 947 ms
// 실패 목록: [timeout id=250, timeout id=500, timeout id=750, timeout id=1000]
// 이론값: 플랫폼 = 1000/16 × 50ms ≈ 3150ms, 가상 ≈ 50msrun() 을 직접 호출Thread t = new Thread(() -> heavyWork());
t.run(); // 새 스레드가 아니라 현재 스레드에서 그냥 실행됨run() 은 평범한 메서드입니다. 병렬성이 전혀 생기지 않는데 코드는 멀쩡해 보여서 오래 눈치 못 챕니다.
✅
Thread t = new Thread(() -> heavyWork());
t.start(); // OS 스레드 생성 → 그 스레드가 run() 호출volatile 로 count++ 보호private volatile int count;
public void hit() { count++; } // 여전히 갱신 손실 발생volatile 은 가시성만 보장합니다. 읽기-더하기-쓰기 세 단계 사이에 다른 스레드가 끼어드는 것은 막지 못합니다.
✅
private final AtomicInteger count = new AtomicInteger();
public void hit() { count.incrementAndGet(); }
// 또는 synchronized 블록submit() 하고 Future.get() 을 안 함 → 예외 실종pool.submit(() -> { processPayment(order); }); // 안에서 예외가 나도 아무 로그도 없음submit 은 예외를 Future 안에 담아 두고, 아무도 get() 을 안 하면 그대로 사라집니다. 결제가 실패했는데 성공한 줄 아는 사고가 납니다.
✅
Future<?> f = pool.submit(() -> processPayment(order));
try { f.get(); } catch (ExecutionException e) { log.error("payment failed", e.getCause()); }
// 결과가 필요 없으면 execute() 를 쓰고 UncaughtExceptionHandler 를 설정하거나, 작업 안에서 try-catchshutdown() 누락 → JVM 이 안 끝남ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(task);
// main 이 끝나도 워커 스레드(non-daemon)가 살아 있어 프로세스가 종료되지 않음✅
try (ExecutorService pool = Executors.newFixedThreadPool(4)) { // JDK 19+
pool.submit(task);
} // close() → shutdown() + awaitTermination()
// 구버전: finally { pool.shutdown(); pool.awaitTermination(30, SECONDS); }synchronized void transferTo(Account other, long amt) {
synchronized (other) { ... } // this → other 순서. 반대 방향 호출과 만나면 데드락
}락을 잡은 채 다른 락을 잡으면 순환 대기 조건이 성립할 수 있습니다.
✅
// 전역 순서(예: id) 로 정렬해서 항상 같은 순서로 잠근다 (예제 2 참고)
// 또는 tryLock(timeout) 으로 실패 시 전부 해제 후 재시도remove() 안 함CURRENT_USER.set(user);
handle(request);
// remove 없음 → 이 워커 스레드가 다음 요청을 처리할 때 이전 사용자가 보임✅
CURRENT_USER.set(user);
try { handle(request); }
finally { CURRENT_USER.remove(); }ExecutorService pool = Executors.newFixedThreadPool(200, Thread.ofVirtual().factory()); // 의미 없음가상 스레드는 싸니까 작업마다 하나씩 만드는 것이 설계 의도입니다. 200개로 제한하면 이점이 사라집니다. 동시성 상한이 필요하면 Semaphore 로 제어합니다.
✅
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
Semaphore limit = new Semaphore(50); // 외부 API 동시 호출 50개 제한
for (var req : requests) ex.submit(() -> { limit.acquire(); try { call(req); } finally { limit.release(); } });
}RequestCounter 클래스를 만드세요. hit(String path) 는 경로별 호출 수를 세고, snapshot() 은 Map<String, Integer> 를 반환합니다. 8개 스레드가 각각 /a, /b 를 10,000번씩 호출한 뒤 결과가 정확히 80,000 / 80,000 이 되도록 하세요. ConcurrentHashMap.merge 를 사용하세요.
import java.util.*;
import java.util.concurrent.*;
public class Ex1 {
static class RequestCounter {
private final ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
void hit(String path) { counts.merge(path, 1, Integer::sum); } // merge 는 원자적
Map<String, Integer> snapshot() { return new TreeMap<>(counts); }
}
public static void main(String[] args) throws Exception {
RequestCounter c = new RequestCounter();
try (var pool = Executors.newFixedThreadPool(8)) {
for (int t = 0; t < 8; t++)
pool.submit(() -> { for (int i = 0; i < 10_000; i++) { c.hit("/a"); c.hit("/b"); } });
}
System.out.println(c.snapshot());
}
}
// 출력:
// {/a=80000, /b=80000}외부 API 호출을 흉내 내는 String fetch(int id) (200ms sleep 후 "item-" + id 반환) 를 20번 호출해야 합니다. (1) 순차 호출 (2) 가상 스레드로 병렬 호출 두 가지를 구현하고, 각각의 소요 시간이 약 4초 vs 약 0.2초임을 출력하세요. 결과 리스트는 id 순서를 유지해야 합니다.
import java.util.*;
import java.util.concurrent.*;
public class Ex2 {
static String fetch(int id) {
try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
return "item-" + id;
}
public static void main(String[] args) throws Exception {
long t0 = System.currentTimeMillis();
List<String> seq = new ArrayList<>();
for (int i = 0; i < 20; i++) seq.add(fetch(i));
System.out.println("sequential ~" + (System.currentTimeMillis() - t0) / 1000 + "s, " + seq.size());
t0 = System.currentTimeMillis();
List<Future<String>> fs = new ArrayList<>();
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 20; i++) { int id = i; fs.add(ex.submit(() -> fetch(id))); }
}
List<String> par = new ArrayList<>();
for (Future<String> f : fs) par.add(f.get()); // submit 순서 = id 순서
System.out.println("parallel ~" + (System.currentTimeMillis() - t0) / 1000 + "s, " + par.get(19));
}
}
// 출력:
// sequential ~4s, 20
// parallel ~0s, item-19BoundedBuffer<T> 를 ReentrantLock 과 두 개의 Condition(notFull, notEmpty) 으로 구현하세요. put 은 가득 차면 대기, take 는 비면 대기합니다. 용량 2 버퍼에 생산자 1개가 1~5 를 넣고 소비자 1개가 꺼내 합계 15 를 출력하세요.
import java.util.*;
import java.util.concurrent.locks.*;
public class Ex3 {
static class BoundedBuffer<T> {
private final Deque<T> items = new ArrayDeque<>();
private final int capacity;
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
BoundedBuffer(int capacity) { this.capacity = capacity; }
void put(T t) throws InterruptedException {
lock.lock();
try {
while (items.size() == capacity) notFull.await(); // while: 허위 깨어남(spurious wakeup) 대비
items.addLast(t);
notEmpty.signal();
} finally { lock.unlock(); }
}
T take() throws InterruptedException {
lock.lock();
try {
while (items.isEmpty()) notEmpty.await();
T t = items.pollFirst();
notFull.signal();
return t;
} finally { lock.unlock(); }
}
}
public static void main(String[] args) throws Exception {
BoundedBuffer<Integer> buf = new BoundedBuffer<>(2);
int[] sum = {0};
Thread producer = new Thread(() -> { try { for (int i = 1; i <= 5; i++) buf.put(i); } catch (InterruptedException e) {} });
Thread consumer = new Thread(() -> { try { for (int i = 0; i < 5; i++) sum[0] += buf.take(); } catch (InterruptedException e) {} });
producer.start(); consumer.start();
producer.join(); consumer.join();
System.out.println("sum = " + sum[0]);
}
}
// 출력:
// sum = 15count++ 는 읽기-계산-쓰기 3단계라 끼어들기가 가능하다(경쟁 조건). 해결은 공유 안 하기 / 원자화(Atomic, CAS) / 상호 배제(synchronized, Lock) 셋 중 하나.synchronized 는 원자성 + 가시성, volatile 은 가시성만. 데드락은 4조건이 모두 성립할 때만 나며, 락 순서 고정이 가장 실용적인 예방책이다.ExecutorService 로. submit 의 예외는 get() 해야 보이고, shutdown + awaitTermination(또는 try-with-resources) 로 반드시 종료한다.다음 레슨 03. 람다에서는 Runnable, Callable 처럼 이 레슨에서 이미 쓰고 있던 함수형 인터페이스의 정체와 람다가 어떻게 컴파일되는지 다룹니다.