Java NiO is used in jdk1.4, which can be said to be "new IO", or non-blocking I/O. Here's how Java NIO works:
-
All IO events are handled by a dedicated thread and are responsible for distribution.
-
Event-driven: events are triggered when they arrive, rather than synchronized to monitor events.
-
Thread communication: The threads communicate through wait,notify and other means. Ensure that each context switch is meaningful. Reduce unnecessary thread switching.
After reading some of the information, I'll stick to the schematic diagram of the Java NiO I understand:
Note: The processing process for each thread is probably read data, decoding, calculation processing, encoding, sending the response.
The Java NiO server only needs to start a dedicated thread to handle all IO events, how is this communication model implemented? Hehe, let's explore its mysteries together. Java NIO uses two-way channels (channel) for data transfer, rather than unidirectional streaming (stream), where events of interest can be registered on the channel. There are four types of events:
Event name
|
corresponding values
|
Server-side Receive client connection events
|
Selectionkey.op_accept (16)
|
Client Connection service-side events
|
Selectionkey.op_connect (8)
|
Read Events
|
Selectionkey.op_read (1)
|
Write events
|
Selectionkey.op_write (4)
|
The server and the client each maintain a management channel object, which we call selector, which detects events on one or more channels (channel). We take the server as an example, if the service side of the selector register a read event, at some point the client sends some data to the service side, blocking I/O then calls the Read () method to block the read data, and the service side of NIO will add a read event in the selector. The service-side processing thread polls the selector and, if an event of interest is found when accessing selector, handles these events and, if no event of interest arrives, the processing thread blocks until the event of interest arrives. Here's what I understand about the communication model of Java NIO:
To better understand Java NIO, the following is a simple code implementation of the server and client:
Java NIO principle and communication model