[java] 자바에서 제공하는 비동기 IO 관련 클래스와 인터페이스

자바에서는 비동기 IO를 처리하기 위해 다양한 클래스와 인터페이스를 제공합니다. 이들을 사용하여 효율적이고 빠른 비동기 IO를 구현할 수 있습니다.

1. java.nio 패키지

1.1. Selector

Selector는 비동기 IO를 처리하는 핵심 클래스 중 하나입니다. Selector를 사용하면 하나의 쓰레드로 여러 개의 소켓 채널을 관리할 수 있습니다. Selector는 이벤트들에 대한 관심을 등록하고, 해당 이벤트가 발생하면 처리할 수 있습니다.

Selector selector = Selector.open();
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);

1.2. Channel

Channel은 입출력을 수행하는 인터페이스입니다. FileInputStream, FileOutputStream, SocketChannel 등 다양한 종류의 Channel이 제공됩니다. Channel을 통해 비동기적으로 입출력을 수행할 수 있습니다.

Path file = Paths.get("path/to/file");
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
fileChannel.read(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() {
    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        // 읽기가 완료되었을 때의 처리 로직
    }
    
    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        // 읽기 실패시의 처리 로직
    }
});

2. java.util.concurrent 패키지

2.1. ExecutorService

ExecutorService는 비동기 작업을 처리하기 위한 인터페이스입니다. 여러 작업을 동시에 실행하고, 작업의 완료를 기다릴 수 있습니다. ExecutorService를 사용하면 스레드 풀을 효율적으로 관리할 수 있습니다.

ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.submit(() -> {
    // 작업 처리 로직
});

2.2. CompletableFuture

CompletableFuture는 비동기적인 작업의 결과를 처리하기 위한 클래스입니다. 여러 개의 작업을 연결하거나, 작업 결과에 대한 다양한 조작을 수행할 수 있습니다. CompletableFuture는 자바 8부터 추가된 클래스로, 간편하게 비동기 코드를 작성할 수 있습니다.

CompletableFuture.supplyAsync(() -> {
    // 작업 처리 로직
    return 결과;
}).thenApplyAsync(result -> {
    // 전 단계 작업의 결과를 가지고 추가 작업 처리 로직
    return 수정된_결과;
}).thenAcceptAsync(result -> {
    // 최종 작업 결과를 처리하는 로직
});

3. 참고 자료