By reading the Java Io source code, you can find the basic architecture of Io. Note: This article is purely intended to record and share what you have learned. Some images and code are from other blogs. Sorry, I hope that people who have read this blog can leave your comments and give them a learning opportunity. Thank you very much !!!
* Byte-based Io interfaces: inputstream and outputstream
*
* Character-based operations: reader and writer
*
* Disk-based I/O interface: File
*
* Network-based IO Interface: Socket
*
* Character decoding Class Structure
*
* Character encoding-related Class Structure
*
*
Disk Io Working Mechanism
* (1) standard file access method
* To access disk files, you need to call the interface of the operating system. The program can only access physical devices by calling the operating system.
* The user address space and the address switching of the system kernel space may occur when an operating system call is used. (The operating system isolates the address space of the kernel program from the application address space to ensure the system's operation security. ).
* The standard file access method is that when you call the read () interface, the operating system checks whether the cache of the kernel has been cached. If yes, the system returns the cache directly, otherwise, the data is read from the disk and then cached to your application cache.
* The write operation is to copy data from the user's address space to the kernel's tell page cache. The system determines when to copy data to the disk. The application can call sync for explicit synchronization.
*
* (2) Direct File Access
* Direct IO access means that the application directly accesses the disk space without passing through the kernel cache of the operating system. This reduces the replication from the kernel cache to the application cache.
*
* (3) Synchronous File Access
* The synchronous access to files is the mark that the file is successfully written only when it is written to the disk space.
*
* (4) asynchronous File Access
* For asynchronous file access, when an application sends a read () request, it does not need to block waiting for the kernel cache to write the aggregation into the application cache,
* When the requested data is returned, it will continue to process the requested data. The Asynchronous Method only improves the program efficiency, but does not change the file access efficiency.
*
* (5) Address ing
* The Memory ing method is to map files in the disk to a memory address in the operating system. When you want to access this file, the data in the memory is directly converted to a certain segment of data to access the file.
* The purpose is to reduce data replication from memory space to user address space.
*
*
* Java access to Disk Files
* Virtual File object, FileDescripter
*
* Java serialization Technology
* General Data Structure: JSON XML
*-
*
How NIO works
*
* The traditional I/O method may block file access. Once the current thread is blocked, the CPU usage will be lost. When a thread is created through each connection,
* Blocking only blocks one thread and does not affect other jobs. To avoid the occupation of system resources by frequent threads, you can establish a thread pool.
* Reduce system resource overhead,
*
* NIO-related class diagram
*
An example of NIO
/*** NIO server *** In the NIO database, all data is processed using a buffer. * When reading data, it is directly read into the buffer zone. When writing data, it is written to the buffer. When you access the data in NIO at any time, you put it in the buffer zone. The buffer is essentially an array. It is usually a byte array, but other types of arrays can also be used. However, a buffer zone is not just an array. The buffer zone provides structured access to data, and supports tracking system read/write processes. * **/Public class NIOServer {// channel manager private Selector selector;/*** get a ServerSocket channel, perform Initialization on the channel * @ param port bound port Number * @ throws IOException */public void initServer (int port) throws IOException {// get a ServerSocket channel ServerSocketChannel serverChannel = ServerSocketChannel. open (); // set the channel to non-blocking serverChannel. configureBlocking (false); // bind the ServerSocket corresponding to the channel to the port serverChannel. socket (). Bind (new InetSocketAddress (port); // obtain a channel manager this. selector = Selector. open (); // bind the channel manager to the channel and register SelectionKey for the channel. OP_ACCEPT event, after the event is registered, // when the event arrives, selector. select () will return, if the event does not reach selector. select () will be blocked all the time. ServerChannel. register (selector, SelectionKey. OP_ACCEPT);}/*** use round robin to listen for events to be processed on the selector. If yes, then process * @ throws IOException */@ SuppressWarnings ("unchecked") public void listen () throws IOException {System. out. println ("server started successfully! "); // Round-robin access selector while (true) {// The method returns when the registered event arrives; otherwise, the method will always block selector. select (); // gets the Iterator of the selected item in the selector. The selected item is the registered event Iterator ite = this. selector. selectedKeys (). iterator (); while (ite. hasNext () {SelectionKey key = (SelectionKey) ite. next (); // Delete the selected key to prevent repeated processing of ite. remove (); // client request connection event if (key. isAcceptable () {ServerSocketChannel server = (ServerSocketChannel) key. channel (); // obtain the Sock channel connected to the client EtChannel channel = server. accept (); // set to non-blocking channel. configureBlocking (false); // here you can send messages to the client. write (ByteBuffer. wrap (new String ("sent a message to the client "). getBytes (); // after the connection to the client is successful, you must set the read permission for the channel to receive client information. Channel. register (this. selector, SelectionKey. OP_READ); // get readable events} else if (key. isReadable () {read (key );}}}} /*** event for processing the information sent from the client * @ param key * @ throws IOException */public void read (SelectionKey key) throws IOException {// the server can read the message: obtain the Socket channel SocketChannel = (SocketChannel) key of the event. channel (); // create the read buffer ByteBuffer buffer = ByteBuffer. allocate (10); channel. read (buffer); byte [] data = buffer. array (); String msg = new String (data ). trim (); System. out. println ("message received by the server:" + msg); ByteBuffer outBuffer = ByteBuffer. wrap (msg. getBytes (); channel. write (outBuffer); // send the message back to the client}/*** start the server test * @ throws IOException */public static void main (String [] args) throws IOException {NIOServer server = new NIOServer (); server. initServer (8000); server. listen ();}}
/*** NiO client */public class nioclient {// channel manager private selector;/*** get a socket channel, perform Initialization on the channel * @ Param IP connection Server IP * @ Param port connection server port * @ throws ioexception */Public void initclient (string IP, int port) throws ioexception {// obtain a socket channel socketchannel channel = socketchannel. open (); // set the channel to be non-blocking channel. configureblocking (false); // obtain a channel manager this. selector = selector. open ();/ /The client connects to the server. In fact, the method execution does not implement the connection. You need to call the/channel in the listen () method. finishconnect (); to connect to the channel. connect (New inetsocketaddress (IP, Port); // bind the channel manager to the channel and register the selectionkey for the channel. op_connect event. Channel. register (selector, selectionkey. op_connect);}/*** use polling to listen for events to be processed on the selector. If yes, then process * @ throws ioexception */@ suppresswarnings ("unchecked") Public void listen () throws ioexception {// round-robin access selector while (true) {// select a group of events that can perform I/O operations and put them in selector. The method on the client is not blocked. // The method on the server is different from that on the server, you can view the API comments. when at least one channel is selected, the // selector's Wakeup method is called and the method is returned. for the client, the channel is always the selected selector. select (); // obtain the iterations of the items in the selector. Generator iterator ite = This. selector. selectedkeys (). iterator (); While (ITE. hasnext () {selectionkey key = (selectionkey) ite. next (); // Delete the selected key to prevent repeated processing of ITE. remove (); // connection event occurs if (key. isconnectable () {socketchannel channel = (socketchannel) Key. channel (); // If the connection is in progress, the connection if (channel. isconnectionpending () {channel. finishconnect ();} // set to non-blocking channel. configureblocking (false); // here you can send messages to the server, channe L. write (bytebuffer. wrap (new string ("sent a message to the server "). getbytes (); // after the connection to the server is successful, you must set the read permission for the channel to receive information from the server. Channel. register (this. selector, selectionkey. op_read); // get readable events} else if (key. isreadable () {read (key );}}}} /*** event for processing the information sent from the server * @ Param key * @ throws ioexception */Public void read (selectionkey key) throws ioexception {// The same as the read method on the server}/*** start the client test * @ throws ioexception */public static void main (string [] ARGs) throws ioexception {nioclient client = new nioclient (); client. initclient ("localhost", 8000); client. listen ();}}
How the buffer works:
* By reading ByteBuffer source code, you can know that it is implemented through the underlying byte array, which includes four fields: limit (limit), position (position), mark (mark), and capacity (capacity ).
*
* You can use ByteBuffer. allocate (size) or ByteBuffer. allocateDirect (size) to create a buffer,
* The former HeapByteBuffer is created in the java memory, and data needs to be copied between the user address space and the operating system address space. java GC is collected and the creation and recovery costs are low.
* The latter (DirectByteBuffer) is the buffer associated with the underlying storage space and does not need to be copied. However, you need to release the DirectByteBuffer memory referenced by the java object through System. gc ().
* Memory leakage may occur, causing high overhead for creation and recovery.
*
NIO Data Access Method
*
* NIO provides two better ways to access files:
* FileChannel. transferTo (), FileChannel. transferFrom ()
* These two methods move data directly in the memory address space, reducing the replication from the memory address space to the user address space.
*
* FileChannel. map ()
* Maps files to a memory area. Applications can directly operate on files when accessing this memory area, saving the loss of copying from the memory address space to the user address space. It is suitable for read-only operations on large files.
* The specific implementation is related to MappedByteBuffer. You can refer to its source code.
*
/*** File copy * @ param srcfilePath source file path * @ param targetPath target file path * @ throws IOException */private static void copy (String srcfilePath, String targetPath) throws IOException {File file = new File (targetPath); if (! File. getParentFile (). exists () {file. mkdirs ();} FileChannel inFileChannel = new RandomAccessFile (srcfilePath, "r "). getChannel (); // obtain the source file channel MappedByteBuffer inMappedByteBuffer = inFileChannel. map (MapMode. READ_ONLY, 0, inFileChannel. size (); // map it To the memory space inFileChannel. close (); FileChannel outFileChannel = new RandomAccessFile (targetPath, "rw "). getChannel (); // get the file channel of the target file MappedByteBuffer outMappedByteBuffer = outFileChannel. map (MapMode. READ_WRITE, 0, inMappedByteBuffer. capacity (); // map the memory space outMappedByteBuffer. put (inMappedByteBuffer); outFileChannel. close ();} /*** add content to the disk * @ param file the File to be appended * @ param str the string to be appended * @ throws IOException */public static void add (file File, string str) throws IOException {FileChannel channel = new RandomAccessFile (file, "rw "). getChannel (); // get the file channel byte [] bytes = str. getBytes (); // The Byte content to be appended int length = bytes. length; // The length of the byte // map the file to the memory to MappedByteBuffer map = channel. map (MapMode. READ_WRITE, 0, channel. size () + length); int position = map. limit ()-length; // obtain the location map corresponding to the map pointer. position (position); map. put (bytes); map. force (); // force it to synchronize disk content, not required; channel. close ();}
**/