Java I/O Models and Applications (Part 2)
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:
- Return
java.util.concurrent.Future
instances - 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
- Study notes of JAVA NIO - architecture briefings
- Java IO architecture
- Java in a nutshell
- Java非阻塞IO和异步IO
- Chapter 6. I/O Multiplexing: The select and poll Functions, Unix Network Programming, Volume 1: The Sockets Networking API (3rd Edition)