Asynchronous IO for Files

NIO.2 was published in JDK 1.7 with two major new features: Asynchronous I/O interfaces and Paths file-related interfaces. The Java implementation of asynchronous I/O model includes:

  1. Return java.util.concurrent.Future instances
  2. Use java.nio.channels.CompletionHandler interface to provide a callback reference

Here is an example with CompletionHandler.

The execution result may be this:

[Thread is: Thread[main,5,main]]
[Thread is: Thread[Thread-0,5,main]]
It is a beautiful day!

It is clear that the task is handled by a different thread (“Thread-0” in “main” thread group). In fact, the asynchronous channels are linked with a thread pool. The tasks will be submitted to the thread pool, and the routine will then be dispatched to completed or failed in CompletionHandler, depending on the execution result.

The default thread pool can be specified by system properties via AsynchronousChannelGroup class. If it is not configured, Java will use a system-dependent shared thread pool.

References

  1. Study notes of JAVA NIO - architecture briefings
  2. Java IO architecture
  3. Java in a nutshell
  4. Java非阻塞IO和异步IO
  5. Chapter 6. I/O Multiplexing: The select and poll Functions, Unix Network Programming, Volume 1: The Sockets Networking API (3rd Edition)