반응형
많은 사람들이 비동기라고 하면 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
'Programming > Java' 카테고리의 다른 글
Java 메일 Library 들 (0) | 2024.08.21 |
---|---|
Velocity 를 이용한 템플릿 작성 (1) | 2024.08.19 |
원시 타입(Primitive type)과 래퍼 클래스(Wrapper class) (29) | 2024.07.31 |
TCP 소켓 통신 (0) | 2024.07.30 |
Camel Case , Snake Case, Pascal Case 에 대하여 (0) | 2024.07.26 |