본문 바로가기
Programming/Java

JAVA 비동기처리 CompletableFuture

by d-e-v-j 2024. 8. 5.
반응형

많은 사람들이 비동기라고 하면 AJAX를 떠올린다. 

Java 에서도 비동기로 처리해주는 명령어가 있다.


CompletableFuture라는 명령어 인데 이는 비동기 프로그래밍으로 서버의 응답시간을 줄이고, 더 나은 사용자 경험을 제공해준다. Java 8 버전에 도입된 처리 도구로 비동기 작업을 처리하고, 콜백을 사용하여 작업 완료 후의 동작을 정의할 수 있다.

 

1.CompletableFuture 생성

 

  • CompletableFuture.runAsync(Runnable) : 반환값이 없는 비동기 작업을 실행.
  • CompletableFuture.supplyAsync(Supplier<U>) : 반환값이 있는 비동기 작업을 실행.

 

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        // 반환값이 없는 비동기 작업
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("Task 1 completed");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 반환값이 있는 비동기 작업
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
                return "Task 2 completed";
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        });

        // 다른 작업 수행
        System.out.println("Doing something else while tasks are executing...");
    }
}

 

2.콜백 사용

 

  • thenApply(Function<? super T,? extends U>) : 결과를 변환.
  • thenAccept(Consumer<? super T>) : 결과를 소비.
  • thenRun(Runnable) : 결과를 사용하지 않고 작업을 실행.
import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
                return "Task completed";
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        }).thenApply(result -> {
            return result.toUpperCase();
        }).thenAccept(result -> {
            System.out.println(result);
        });

        System.out.println("Doing something else while the task is executing...");
    }
}

 

3.예외 처리

  • exceptionally 메서드를 사용하여 예외를 처리
import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
                if (true) {
                    throw new RuntimeException("Exception occurred");
                }
                return "Task completed";
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        }).exceptionally(ex -> {
            System.out.println("Error: " + ex.getMessage());
            return "Default Value";
        }).thenAccept(result -> {
            System.out.println(result);
        });

        System.out.println("Doing something else while the task is executing...");
    }
}

 

4. 작업 조합

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
                if (true) {
                    throw new RuntimeException("Exception occurred");
                }
                return "Task completed";
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        }).exceptionally(ex -> {
            System.out.println("Error: " + ex.getMessage());
            return "Default Value";
        }).thenAccept(result -> {
            System.out.println(result);
        });

        System.out.println("Doing something else while the task is executing...");
    }
}

 

5.작업 완료 후 처리

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
                return "Task 1 completed";
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        });

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                return "Task 2 completed";
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        });

        CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2);

        combinedFuture.thenRun(() -> {
            System.out.println("All tasks completed");
        });

        System.out.println("Doing something else while the tasks are executing...");
    }
}

 

CompletableFuture 을 사용하여 Java 애플리케이션의 비동기 처리를 구현 해보자.

 

728x90
반응형
LIST