Java Java7

CompletionHandler in AIO

CompletionHandler in AIO

CompletionHandler in AIO

CompletionHandler is an interface used to consume the result of an asynchronous I/O operation via a callback mechanism.

How it Works

It defines two methods: completed() for success and failed() for errors. This model allows for cleaner code than polling Future objects and is more efficient for high-throughput systems.

Java Example

import java.nio.channels.CompletionHandler;

public class HandlerExample {
    public static void main(String[] args) {
        CompletionHandler<Integer, String> handler = new CompletionHandler<Integer, String>() {
            public void completed(Integer result, String attachment) {
                System.out.println(attachment + " success: " + result);
            }
            public void failed(Throwable exc, String attachment) {
                exc.printStackTrace();
            }
        };
        System.out.println("Handler defined for async ops.");
    }
}

Output

Handler defined for async ops.

Key Points

  • Callback-based async I/O
  • Separate methods for success and failure
  • Supports 'attachment' objects for context
  • Core part of NIO.2 AIO
Topics: Java Java7
← Newer Post Older Post →