Java 1.7版本中引入了NIO2(即AIO)。NIO(New IO)是Java 1.4版本中引入的一種非堵塞IO模型,而AIO(Asynchronous IO)則是在NIO基礎(chǔ)上發(fā)展而來(lái)。相比于傳統(tǒng)的同步IO模型,AIO的最大優(yōu)點(diǎn)在于它能夠在IO操作進(jìn)行的同時(shí)進(jìn)行其他操作(多路復(fù)用),從而提高了系統(tǒng)的吞吐量。
在使用AIO時(shí),需要使用AsynchronousChannelGroup和AsynchronousFileChannel來(lái)進(jìn)行文件的異步讀寫。下面是一個(gè)簡(jiǎn)單的AIO文件讀取示例代碼:
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.channels.CompletionHandler; import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class AioFileReader { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { Path path = Paths.get("test.txt"); AsynchronousFileChannel channel = AsynchronousFileChannel.open(path); ByteBuffer buffer = ByteBuffer.allocate(1024); long position = 0; Futureoperation = channel.read(buffer, position); while (!operation.isDone()) { System.out.println("Waiting for task to complete..."); } buffer.flip(); byte[] data = new byte[buffer.limit()]; buffer.get(data); System.out.println(new String(data)); channel.close(); } }
除了AIO外,NIO中還有一個(gè)重要的組件是Selector。Selector是一個(gè)可以同時(shí)監(jiān)控多個(gè)通道的對(duì)象,當(dāng)某個(gè)通道上的事件被觸發(fā)后,Selector就會(huì)返回,從而實(shí)現(xiàn)了一種單線程可以同時(shí)處理多個(gè)通道的模式,大大提高了系統(tǒng)的效率。
下面是一個(gè)簡(jiǎn)單的NIO文件讀取示例代碼:
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class NioSocketClient { public static void main(String[] args) throws IOException { SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress("localhost", 8080)); while (!socketChannel.finishConnect()) { // Wait for connection } ByteBuffer buffer = ByteBuffer.allocate(1024); socketChannel.read(buffer); buffer.flip(); byte[] data = new byte[buffer.limit()]; buffer.get(data); System.out.println(new String(data)); socketChannel.close(); } }
在這個(gè)示例中,使用了非堵塞IO模型,通過(guò)SocketChannel來(lái)實(shí)現(xiàn)網(wǎng)絡(luò)通信,通過(guò)ByteBuffer進(jìn)行數(shù)據(jù)讀寫。