고급 스레딩 패턴

Java 코드 최적화

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

스레드 풀 기초

스레드 생성에는 비용이 많이 듭니다!

$$

스레드 풀:

  • 기존 스레드를 재사용합니다
  • 동시 실행 스레드 수를 제어합니다
  • ExecutorService 인터페이스로 관리됩니다
Java 코드 최적화

스레드 풀 생성

// Fixed thread pool with 4 threads
ExecutorService fixedPool = Executors.newFixedThreadPool(4);


// Cached thread pool that grows as needed ExecutorService cachedPool = Executors.newCachedThreadPool();
// Single-threaded executor ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
Java 코드 최적화

작업 제출

ExecutorService executor = Executors.newFixedThreadPool(4);

// Submit a task with no return value
executor.execute(() -> System.out.println("Simple task"));

// Submit a task with a return value (Callable)
Future<Integer> future = executor.submit(() -> {
    Thread.sleep(1000);
    return 42;
});

// Get result from Future (blocks until complete)
int result = future.get();
Java 코드 최적화

Executor 종료

// Signal shutdown, but continue running existing tasks
executor.shutdown();


// Wait for termination (with timeout) boolean terminated = executor.awaitTermination(5, TimeUnit.SECONDS);
// Force immediate shutdown, canceling running tasks executor.shutdownNow();
Java 코드 최적화

CompletableFuture 알아보기

  • CompletableFuture
  • Java 8부터 제공되는 Java 동시성 API의 일부입니다
  • 비동기 프로그래밍을 위한 현대적인 접근 방식입니다
  • 수동으로 또는 Function을 통해 완료할 수 있습니다
  • 콜백으로 작업을 연결할 수 있습니다
  • 명시적인 스레드 풀 유무와 관계없이 작동합니다
Java 코드 최적화

CompletableFuture 생성하기

// Run async with default executor
CompletableFuture<Void> runAsync = 
    CompletableFuture.runAsync(() -> performTask());

// Supply async with custom executor ExecutorService executor = Executors.newCachedThreadPool(); CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> fetchData(), executor);
Java 코드 최적화

작업 연결하기

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> fetchUserData(userId))
    .thenApply(data -> extractUsername(data))
    .exceptionally(ex -> "Unknown user");

// Access to result when ready
future.thenAccept(result -> System.out.println(result));
Java 코드 최적화

연습해 봅시다!

Java 코드 최적화

Preparing Video For Download...