Before JDK1.4, I/O input and output processing, we call it old I/O processing, at the beginning of JDK1.4, Java provides a series of improved new input/output features, called New I/O, and a number of new classes for processing input/output, all of which are placed in theJava.nio Bag and sub-package, and many of the classes in the original Java.io package were rewritten based on NIO, adding new capabilities to meet the new I/O. The main differences between Java NiO and IO
| Io |
Nio |
Stream oriented |
Buffer oriented |
|
|
Non-blocking IO |
|
|
Selector Selector |
Buffered (buffer-oriented)
In the entire Java heart I/O, operations are performed in buffers, which greatly improve the performance of the operation.
Operation
There is a series of state variables in buffer, and this state variable may be conceptually written or read, and in the buffer Kaiyuan use is three values representing the state of the buffer.
- Position: Represents the next buffer read or write operation pointer, not to buffer China when writing data, this pointer will change, the pointer is always placed after the last element written. That is: If you write data in 4 locations, Posotion points to the 5th position.
- Limit: Indicates how much data can be stored or read, Position<=limit
- Capacity: Represents the maximum capacity of the buffer, limit<=capacity, which is set when the buffer is allocated. Generally does not change.
To create a buffer:
ImportJava.nio.IntBuffer; Public classintbufferdemo{ Public Static voidMain (String args[]) {intbuffer buf= Intbuffer.allocate (10);//prepare a buffer of 10 sizesSystem.out.print ("1, position, limit, and capacity before writing the data:") ; System.out.println ("Position =" + buf.position () + ", limit =" + buf.limit () + ", Capacty =" +buf.capacity ()); intTemp[] = {5,7,9};//define an int arrayBuf.put (3);//set up a dataBuf.put (temp);//at this point, four records have been storedSystem.out.print ("2, position, limit, and capacity after the data is written:") ; System.out.println ("Position =" + buf.position () + ", limit =" + buf.limit () + ", Capacty =" +buf.capacity ()); Buf.flip (); //Resetting buffers//postion = 0, limit = original positionSystem.out.print ("3, position, limit, and capacity when preparing to output data:") ; System.out.println ("Position =" + buf.position () + ", limit =" + buf.limit () + ", Capacty =" +buf.capacity ()); System.out.print ("Contents in Buffer:") ; while(Buf.hasremaining ()) {intx =Buf.get (); System.out.print (x+ ",") ; } }}
If a buffer is created, the JVM can perform native IO operations directly on it
ImportJava.nio.ByteBuffer; Public classbytebufferdemo{ Public Static voidMain (String args[]) {bytebuffer buf= Bytebuffer.allocatedirect (10);//prepare a buffer of 10 sizes byteTemp[] = {1,3,5,7,9};//Set ContentBuf.put (temp);//set up a set of contentBuf.flip (); System.out.print ("Content in the primary buffer:") ; while(Buf.hasremaining ()) {intx =Buf.get (); System.out.print (x+ ",") ; } }}Channels (channel)
The non-blocking mode of Java NIO enables a thread to send requests to read data from a channel, but it can only get the data that is currently available and will not get anything if no data is available. Instead of keeping the thread blocked, the thread can continue to do other things until the data becomes readable. The same is true for non-blocking writes. A thread requests to write some data to a channel, but does not have to wait for it to be fully written, and the thread can do something else at the same time. Threads typically use non-blocking IO idle time to perform IO operations on other channels, so a single thread can now manage multiple input and output channels (channel).
Java NiO channels are similar to streams, but are somewhat different:
- The data can be read from the channel, and the data can be written to the channel. But stream reads and writes are usually one-way.
- Channels can be read and written asynchronously.
- The data in the channel is always read to a buffer first, or it is always written from a buffer.
As mentioned above, the data is read from the channel to the buffer, and the data is written from the buffer to the channel.
The implementation of channel
These are the most important implementations of the channel in Java NIO:
- FileChannel
- Datagramchannel
- Socketchannel
- Serversocketchannel
FileChannel read and write data from a file.
Datagramchannel can read and write data on the network through UDP.
Socketchannel can read and write data in the network via TCP.
Serversocketchannel can listen for incoming TCP connections, like a Web server. A socketchannel is created for each new incoming connection.
bidirectional input and output operations can be done through the channel. There is another way in the channel called Memory Mapping
Comparison of several ways to read in
Randomaccessfile slower fileinputstream slower buffer reads faster
Fastest Memory mapping
FileChannel Memory Map Instance
ImportJava.nio.ByteBuffer;ImportJava.nio.MappedByteBuffer;ImportJava.nio.channels.FileChannel;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.FileInputStream; Public classfilechanneldemo03{ Public Static voidMain (String args[])throwsexception{File File=NewFile ("D:" + File.separator + "Oumyye.txt") ; FileInputStream input=NULL ; Input=Newfileinputstream (file); FileChannel Fin=NULL;//define the input channelFin = Input.getchannel ();//get the input channelMappedbytebuffer MBB =NULL ; MBB= Fin.map (filechannel.mapmode.read_only,0, File.length ()); byteData[] =New byte[(int) File.length ()];//open up space to receive content intFoot = 0 ; while(Mbb.hasremaining ()) {Data[foot+ +] = Mbb.get ();//reading Data} System.out.println (NewString (data));//Output ContentFin.close (); Input.close (); }}
When you manipulate the code above, the write operation can be very risky, because simply changing a single element in the array can simply modify the file on the disk, because the modification data is the same as the data saved on disk.
Selector (Selectors)
The Selector (selector) is a component in Java NIO that detects one or more NIO channels and is able to know whether the channel is ready for a read-write event. In this way, a single thread can manage multiple channel to manage multiple network connections.
Why use selector?
The benefit of using only a single thread to handle multiple channels is that fewer threads are needed to process the channel. In fact, you can process all the channels with just one thread. For the operating system, context switching between threads is expensive, and each thread consumes some of the system's resources, such as memory. Therefore, the less threads you use, the better.
However, it is necessary to keep in mind that modern operating systems and CPUs are performing more and more well in multitasking, so the overhead of multithreading is getting smaller over time. In fact, if a CPU has multiple cores, not using multitasking may be a waste of CPU power. Anyway, the discussion about that design should be in another different article. Here, it is sufficient to know that using selector can handle multiple channels.
Points
Using selector, you can build a non-blocking network service.
Implementing network programs in the new IO depends on the Serversocketchannel class and the Socketchannel
Selector instances
The following uses selector to complete a simple server operation, the server can be listening at the same time on multiple ports, the main function of this server is to return the current time.
Importjava.net.InetSocketAddress;ImportJava.net.ServerSocket;ImportJava.util.Set;ImportJava.util.Iterator;Importjava.util.Date;ImportJava.nio.channels.ServerSocketChannel;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SocketChannel;ImportJava.nio.channels.Selector;ImportJava.nio.channels.SelectionKey; Public classdateserver{ Public Static voidMain (String args[])throwsException {intPorts[] = {8000,8001,8002,8003,8005,8006};//represents five listening portsSelector Selector = Selector.open ();//Find selector through the Open () method for(inti=0;i<ports.length;i++) {Serversocketchannel Initser=NULL ; Initser= Serversocketchannel.open ();//Open the channel for the serverInitser.configureblocking (false) ;//server configured for non-blockingServerSocket Initsock =Initser.socket (); Inetsocketaddress Address=NULL ; Address=NewInetsocketaddress (Ports[i]);//instantiate a binding addressInitsock.bind (address);//Binding for serviceInitser.register (selector,selectionkey.op_accept);//Waiting for connectionSYSTEM.OUT.PRINTLN ("server running," on "+ ports[i] +" Port listening. ") ; } //to receive all generated keys and to determine whether to get the client's output through the connection intKeysadd = 0 ; while((Keysadd=selector.select ()) >0) {//Select a set of keys, and the corresponding channel is readyset<selectionkey> Selectedkeys = Selector.selectedkeys ();//Take out all the generated keysIterator<selectionkey> iter =Selectedkeys.iterator (); while(Iter.hasnext ()) {Selectionkey key= Iter.next ();//Remove each key if(Key.isacceptable ()) {Serversocketchannel Server=(Serversocketchannel) Key.channel (); Socketchannel Client= Server.accept ();//Receive new ConnectionsClient.configureblocking (false) ;//configured as non-blockingBytebuffer outbuf = bytebuffer.allocatedirect (1024);//Outbuf.put ("Current time is:" +NewDate ()). GetBytes ());//set content to bufferOutbuf.flip (); Client.write (OUTBUF); //Output ContentClient.close ();//Close}} selectedkeys.clear (); //Clear all the keys } }}
After the server is complete, you can use the Telnet command to complete a single operational server.
Java Fundamentals---New I/O technology (NIO)