Java NIO(New I/O)是Java SE 1.4開始引入的一種替代傳統(tǒng)Java IO API的新IO API。NIO的設(shè)計(jì)目標(biāo)是通過提供更快、更多功能的IO處理能力來提高Java IO的性能。與傳統(tǒng)IO API不同,NIO可以同時(shí)處理多個(gè)連接,可以通過一個(gè)單獨(dú)的單線程來管理多個(gè)連接,并作為一種非阻塞IO實(shí)現(xiàn)。
Java AIO(Asynchronous I/O)是在Java 7中引入的新IO API。與NIO不同,AIO的設(shè)計(jì)目標(biāo)是提供更好的異步IO支持。AIO的API包括異步執(zhí)行和異步IO,使得程序可以在進(jìn)行IO操作時(shí)同時(shí)執(zhí)行其他任務(wù)。AIO使用了一種完全不同的事件機(jī)制,使得當(dāng)IO操作完成時(shí),它會向程序發(fā)出通知,從而使得程序可以繼續(xù)執(zhí)行其他任務(wù)。
//NIO示例代碼 public void testNIO() throws Exception { Selector selector = Selector.open(); //創(chuàng)建ServerSocketChannel,并監(jiān)聽端口 ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.socket().bind(new InetSocketAddress(1111)); serverChannel.configureBlocking(false); //注冊ServerSocketChannel到selector上,監(jiān)聽ACCEPT事件 serverChannel.register(selector, SelectionKey.OP_ACCEPT); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { selector.select();//等待有事件發(fā)生 Setkeys = selector.selectedKeys();//獲取所有有事件發(fā)生的SelectionKey Iterator keyIterator = keys.iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if (key.isAcceptable()) {//如果是ACCEPT事件,則建立SocketChannel連接 ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel clientChannel = server.accept(); clientChannel.configureBlocking(false); clientChannel.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) {//如果是READ事件,則讀取數(shù)據(jù) SocketChannel clientChannel = (SocketChannel) key.channel(); buffer.clear(); clientChannel.read(buffer); buffer.flip(); System.out.println("received :" + new String(buffer.array())); } keyIterator.remove();//處理完事件后需要移除SelectionKey } } }
//AIO示例代碼 public void testAIO() throws Exception { AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(); server.bind(new InetSocketAddress(1111)); server.accept(null, new CompletionHandler() { @Override public void completed(AsynchronousSocketChannel clientChannel, Object attachment) { ByteBuffer buffer = ByteBuffer.allocate(1024); try { clientChannel.read(buffer, null, new CompletionHandler () { @Override public void completed(Integer result, Object attachment) { buffer.flip(); System.out.println("received :" + new String(buffer.array())); buffer.clear(); clientChannel.close(); server.accept(null, this); } @Override public void failed(Throwable exc, Object attachment) { //... } }); } catch (Exception e) { //... } } @Override public void failed(Throwable exc, Object attachment) { //... } }); }
性能測試結(jié)果顯示,NIO比傳統(tǒng)IO快得多,可以處理更多的連接。而AIO比NIO更快,因?yàn)樗褂昧水惒絀O,讓程序可以在IO操作進(jìn)行時(shí)同時(shí)執(zhí)行其他任務(wù)。但由于AIO是Java 7才開始引入的,因此并不是所有Java版本都支持AIO。