原文出處: 朱小廝
現(xiàn)在使用NIO的場景越來越多亥至,很多網(wǎng)上的技術框架或多或少的使用NIO技術,譬如Tomcat贱迟,Jetty姐扮。學習和掌握NIO技術已經(jīng)不是一個JAVA攻城獅的加分技能,而是一個必備技能衣吠。再者茶敏,現(xiàn)在互聯(lián)網(wǎng)的面試中上點level的都會涉及一下NIO或者AIO的問題(AIO下次再講述,本篇主要講述NIO),掌握好NIO也能幫助你獲得一份較好的offer缚俏。 驅使博主寫這篇文章的關鍵是網(wǎng)上關于NIO的文章并不是很多惊搏,而且案例較少,針對這個特性忧换,本文主要通過實際案例主要講述NIO的用法恬惯,每個案例都經(jīng)過實際檢驗。博主通過自己的理解以及一些案例希望能給各位在學習NIO之時多一份參考亚茬。博主能力有限宿崭,文中有不足之處歡迎指出。
本文持續(xù)更新才写,轉載請保留原文鏈接葡兑。
概述
NIO主要有三大核心部分:Channel(通道)奖蔓,Buffer(緩沖區(qū)), Selector。傳統(tǒng)IO基于字節(jié)流和字符流進行操作讹堤,而NIO基于Channel和Buffer(緩沖區(qū))進行操作吆鹤,數(shù)據(jù)總是從通道讀取到緩沖區(qū)中,或者從緩沖區(qū)寫入到通道中洲守。Selector(選擇區(qū))用于監(jiān)聽多個通道的事件(比如:連接打開疑务,數(shù)據(jù)到達)。因此梗醇,單個線程可以監(jiān)聽多個數(shù)據(jù)通道知允。
NIO和傳統(tǒng)IO(一下簡稱IO)之間第一個最大的區(qū)別是,IO是面向流的叙谨,NIO是面向緩沖區(qū)的温鸽。 Java IO面向流意味著每次從流中讀一個或多個字節(jié)手负,直至讀取所有字節(jié)涤垫,它們沒有被緩存在任何地方。此外竟终,它不能前后移動流中的數(shù)據(jù)挪丢。如果需要前后移動從流中讀取的數(shù)據(jù)晃洒,需要先將它緩存到一個緩沖區(qū)。NIO的緩沖導向方法略有不同农曲。數(shù)據(jù)讀取到一個它稍后處理的緩沖區(qū)趋距,需要時可在緩沖區(qū)中前后移動翰蠢。這就增加了處理過程中的靈活性崔梗。但是陪每,還需要檢查是否該緩沖區(qū)中包含所有您需要處理的數(shù)據(jù)。而且迷守,需確保當更多的數(shù)據(jù)讀入緩沖區(qū)時,不要覆蓋緩沖區(qū)里尚未處理的數(shù)據(jù)旺入。
IO的各種流是阻塞的兑凿。這意味著,當一個線程調(diào)用read() 或 write()時茵瘾,該線程被阻塞礼华,直到有一些數(shù)據(jù)被讀取,或數(shù)據(jù)完全寫入拗秘。該線程在此期間不能再干任何事情了圣絮。 NIO的非阻塞模式,使一個線程從某通道發(fā)送請求讀取數(shù)據(jù)雕旨,但是它僅能得到目前可用的數(shù)據(jù)扮匠,如果目前沒有數(shù)據(jù)可用時捧请,就什么都不會獲取。而不是保持線程阻塞棒搜,所以直至數(shù)據(jù)變的可以讀取之前疹蛉,該線程可以繼續(xù)做其他的事情。 非阻塞寫也是如此力麸。一個線程請求寫入一些數(shù)據(jù)到某通道可款,但不需要等待它完全寫入,這個線程同時可以去做別的事情克蚂。 線程通常將非阻塞IO的空閑時間用于在其它通道上執(zhí)行IO操作闺鲸,所以一個單獨的線程現(xiàn)在可以管理多個輸入和輸出通道(channel)。
Channel
首先說一下Channel埃叭,國內(nèi)大多翻譯成“通道”摸恍。Channel和IO中的Stream(流)是差不多一個等級的。只不過Stream是單向的游盲,譬如:InputStream, OutputStream.而Channel是雙向的误墓,既可以用來進行讀操作,又可以用來進行寫操作益缎。
NIO中的Channel的主要實現(xiàn)有:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
這里看名字就可以猜出個所以然來:分別可以對應文件IO谜慌、UDP和TCP(Server和Client)。下面演示的案例基本上就是圍繞這4個類型的Channel進行陳述的莺奔。
Buffer
NIO中的關鍵Buffer實現(xiàn)有:ByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, ShortBuffer欣范,分別對應基本數(shù)據(jù)類型: byte, char, double, float, int, long, short。當然NIO中還有MappedByteBuffer, HeapByteBuffer, DirectByteBuffer等這里先不進行陳述令哟。
Selector
Selector運行單線程處理多個Channel恼琼,如果你的應用打開了多個通道,但每個連接的流量都很低屏富,使用Selector就會很方便晴竞。例如在一個聊天服務器中。要使用Selector, 得向Selector注冊Channel狠半,然后調(diào)用它的select()方法噩死。這個方法會一直阻塞到某個注冊的通道有事件就緒。一旦這個方法返回神年,線程就可以處理這些事件已维,事件的例子有如新的連接進來、數(shù)據(jù)接收等已日。
FileChannel
看完上面的陳述垛耳,對于第一次接觸NIO的同學來說云里霧里,只說了一些概念,也沒記住什么堂鲜,更別說怎么用了栈雳。這里開始通過傳統(tǒng)IO以及更改后的NIO來做對比,以更形象的突出NIO的用法泡嘴,進而使你對NIO有一點點的了解甫恩。
傳統(tǒng)IO vs NIO
首先,案例1是采用FileInputStream讀取文件內(nèi)容的:
public static void method2(){
InputStream in = null;
try{
in = new BufferedInputStream(new FileInputStream("src/nomal_io.txt"));
byte [] buf = new byte[1024];
int bytesRead = in.read(buf);
while(bytesRead != -1)
{
for(int i=0;i<bytesRead;i++)
System.out.print((char)buf[i]);
bytesRead = in.read(buf);
}
}catch (IOException e)
{
e.printStackTrace();
}finally{
try{
if(in != null){
in.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
輸出結果:(略)
案例是對應的NIO(這里通過RandomAccessFile進行操作酌予,當然也可以通過FileInputStream.getChannel()進行操作):
public static void method1(){
RandomAccessFile aFile = null;
try{
aFile = new RandomAccessFile("src/nio.txt","rw");
FileChannel fileChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
int bytesRead = fileChannel.read(buf);
System.out.println(bytesRead);
while(bytesRead != -1)
{
buf.flip();
while(buf.hasRemaining())
{
System.out.print((char)buf.get());
}
buf.compact();
bytesRead = fileChannel.read(buf);
}
}catch (IOException e){
e.printStackTrace();
}finally{
try{
if(aFile != null){
aFile.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
輸出結果:(略)
通過仔細對比案例1和案例2磺箕,應該能看出個大概,最起碼能發(fā)現(xiàn)NIO的實現(xiàn)方式比叫復雜抛虫。有了一個大概的印象可以進入下一步了松靡。
Buffer的使用
從案例2中可以總結出使用Buffer一般遵循下面幾個步驟:
- 分配空間(ByteBuffer buf = ByteBuffer.allocate(1024); 還有一種allocateDirector后面再陳述)
- 寫入數(shù)據(jù)到Buffer(int bytesRead = fileChannel.read(buf);)
- 調(diào)用filp()方法( buf.flip();)
- 從Buffer中讀取數(shù)據(jù)(System.out.print((char)buf.get());)
- 調(diào)用clear()方法或者compact()方法
Buffer顧名思義:緩沖區(qū),實際上是一個容器建椰,一個連續(xù)數(shù)組雕欺。Channel提供從文件、網(wǎng)絡讀取數(shù)據(jù)的渠道棉姐,但是讀寫的數(shù)據(jù)都必須經(jīng)過Buffer屠列。如下圖:
[圖片上傳失敗...(image-932be4-1545185475985)]
向Buffer中寫數(shù)據(jù):
- 從Channel寫到Buffer (fileChannel.read(buf))
- 通過Buffer的put()方法 (buf.put(…))
從Buffer中讀取數(shù)據(jù):
- 從Buffer讀取到Channel (channel.write(buf))
- 使用get()方法從Buffer中讀取數(shù)據(jù) (buf.get())
可以把Buffer簡單地理解為一組基本數(shù)據(jù)類型的元素列表,它通過幾個變量來保存這個數(shù)據(jù)的當前位置狀態(tài):capacity, position, limit, mark:
索引 | 說明 |
---|---|
capacity | 緩沖區(qū)數(shù)組的總長度 |
position | 下一個要操作的數(shù)據(jù)元素的位置 |
limit | 緩沖區(qū)數(shù)組中不可操作的下一個元素的位置:limit<=capacity |
mark | 用于記錄當前position的前一個位置或者默認是0 |
無圖無真相伞矩,舉例:我們通過ByteBuffer.allocate(11)方法創(chuàng)建了一個11個byte的數(shù)組的緩沖區(qū)笛洛,初始狀態(tài)如上圖,position的位置為0乃坤,capacity和limit默認都是數(shù)組長度苛让。當我們寫入5個字節(jié)時,變化如下圖:
這時我們需要將緩沖區(qū)中的5個字節(jié)數(shù)據(jù)寫入Channel的通信信道湿诊,所以我們調(diào)用ByteBuffer.flip()方法狱杰,變化如下圖所示(position設回0,并將limit設成之前的position的值):
這時底層操作系統(tǒng)就可以從緩沖區(qū)中正確讀取這個5個字節(jié)數(shù)據(jù)并發(fā)送出去了厅须。在下一次寫數(shù)據(jù)之前我們再調(diào)用clear()方法仿畸,緩沖區(qū)的索引位置又回到了初始位置。
調(diào)用clear()方法:position將被設回0朗和,limit設置成capacity错沽,換句話說,Buffer被清空了例隆,其實Buffer中的數(shù)據(jù)并未被清楚,只是這些標記告訴我們可以從哪里開始往Buffer里寫數(shù)據(jù)抢蚀。如果Buffer中有一些未讀的數(shù)據(jù)镀层,調(diào)用clear()方法,數(shù)據(jù)將“被遺忘”,意味著不再有任何標記會告訴你哪些數(shù)據(jù)被讀過唱逢,哪些還沒有吴侦。如果Buffer中仍有未讀的數(shù)據(jù),且后續(xù)還需要這些數(shù)據(jù)坞古,但是此時想要先先寫些數(shù)據(jù)备韧,那么使用compact()方法。compact()方法將所有未讀的數(shù)據(jù)拷貝到Buffer起始處痪枫。然后將position設到最后一個未讀元素正后面织堂。limit屬性依然像clear()方法一樣,設置成capacity∧坛拢現(xiàn)在Buffer準備好寫數(shù)據(jù)了易阳,但是不會覆蓋未讀的數(shù)據(jù)。
通過調(diào)用Buffer.mark()方法吃粒,可以標記Buffer中的一個特定的position潦俺,之后可以通過調(diào)用Buffer.reset()方法恢復到這個position。Buffer.rewind()方法將position設回0徐勃,所以你可以重讀Buffer中的所有數(shù)據(jù)事示。limit保持不變,仍然表示能從Buffer中讀取多少個元素僻肖。
SocketChannel
說完了FileChannel和Buffer, 大家應該對Buffer的用法比較了解了肖爵,這里使用SocketChannel來繼續(xù)探討NIO。NIO的強大功能部分來自于Channel的非阻塞特性檐涝,套接字的某些操作可能會無限期地阻塞遏匆。例如,對accept()方法的調(diào)用可能會因為等待一個客戶端連接而阻塞谁榜;對read()方法的調(diào)用可能會因為沒有數(shù)據(jù)可讀而阻塞幅聘,直到連接的另一端傳來新的數(shù)據(jù)∏灾玻總的來說帝蒿,創(chuàng)建/接收連接或讀寫數(shù)據(jù)等I/O調(diào)用,都可能無限期地阻塞等待巷怜,直到底層的網(wǎng)絡實現(xiàn)發(fā)生了什么葛超。慢速的,有損耗的網(wǎng)絡延塑,或僅僅是簡單的網(wǎng)絡故障都可能導致任意時間的延遲绣张。然而不幸的是,在調(diào)用一個方法之前無法知道其是否阻塞关带。NIO的channel抽象的一個重要特征就是可以通過配置它的阻塞行為侥涵,以實現(xiàn)非阻塞式的信道。
channel.configureBlocking(``false``)
在非阻塞式信道上調(diào)用一個方法總是會立即返回。這種調(diào)用的返回值指示了所請求的操作完成的程度芜飘。例如务豺,在一個非阻塞式ServerSocketChannel上調(diào)用accept()方法,如果有連接請求來了嗦明,則返回客戶端SocketChannel笼沥,否則返回null。
這里先舉一個TCP應用案例娶牌,客戶端采用NIO實現(xiàn)奔浅,而服務端依舊使用IO實現(xiàn)。
客戶端代碼(案例3):
public static void client(){
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketChannel socketChannel = null;
try
{
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("10.10.195.115",8080));
if(socketChannel.finishConnect())
{
int i=0;
while(true)
{
TimeUnit.SECONDS.sleep(1);
String info = "I'm "+i+++"-th information from client";
buffer.clear();
buffer.put(info.getBytes());
buffer.flip();
while(buffer.hasRemaining()){
System.out.println(buffer);
socketChannel.write(buffer);
}
}
}
}
catch (IOException | InterruptedException e)
{
e.printStackTrace();
}
finally{
try{
if(socketChannel!=null){
socketChannel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
服務端代碼(案例4):
public static void server(){
ServerSocket serverSocket = null;
InputStream in = null;
try
{
serverSocket = new ServerSocket(8080);
int recvMsgSize = 0;
byte[] recvBuf = new byte[1024];
while(true){
Socket clntSocket = serverSocket.accept();
SocketAddress clientAddress = clntSocket.getRemoteSocketAddress();
System.out.println("Handling client at "+clientAddress);
in = clntSocket.getInputStream();
while((recvMsgSize=in.read(recvBuf))!=-1){
byte[] temp = new byte[recvMsgSize];
System.arraycopy(recvBuf, 0, temp, 0, recvMsgSize);
System.out.println(new String(temp));
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
try{
if(serverSocket!=null){
serverSocket.close();
}
if(in!=null){
in.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
輸出結果:(略)
根據(jù)案例分析裙戏,總結一下SocketChannel的用法乘凸。
打開SocketChannel:
socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("10.10.195.115",8080));
關閉:
serverSocket.close();
讀取數(shù)據(jù):
String info = "I'm "+i+++"-th information from client";
buffer.clear();
buffer.put(info.getBytes());
buffer.flip();
while(buffer.hasRemaining()){
System.out.println(buffer);
socketChannel.write(buffer);
}
注意SocketChannel.write()方法的調(diào)用是在一個while循環(huán)中的。Write()方法無法保證能寫多少字節(jié)到SocketChannel累榜。所以营勤,我們重復調(diào)用write()直到Buffer沒有要寫的字節(jié)為止。
非阻塞模式下,read()方法在尚未讀取到任何數(shù)據(jù)時可能就返回了壹罚。所以需要關注它的int返回值葛作,它會告訴你讀取了多少字節(jié)。
TCP服務端的NIO寫法
到目前為止猖凛,所舉的案例中都沒有涉及Selector赂蠢。不要急,好東西要慢慢來辨泳。Selector類可以用于避免使用阻塞式客戶端中很浪費資源的“忙等”方法虱岂。例如,考慮一個IM服務器菠红。像QQ或者旺旺這樣的第岖,可能有幾萬甚至幾千萬個客戶端同時連接到了服務器,但在任何時刻都只是非常少量的消息试溯。
需要讀取和分發(fā)蔑滓。這就需要一種方法阻塞等待,直到至少有一個信道可以進行I/O操作遇绞,并指出是哪個信道键袱。NIO的選擇器就實現(xiàn)了這樣的功能。一個Selector實例可以同時檢查一組信道的I/O狀態(tài)摹闽。用專業(yè)術語來說蹄咖,選擇器就是一個多路開關選擇器,因為一個選擇器能夠管理多個信道上的I/O操作付鹿。然而如果用傳統(tǒng)的方式來處理這么多客戶端澜汤,使用的方法是循環(huán)地一個一個地去檢查所有的客戶端是否有I/O操作铝量,如果當前客戶端有I/O操作,則可能把當前客戶端扔給一個線程池去處理银亲,如果沒有I/O操作則進行下一個輪詢,當所有的客戶端都輪詢過了又接著從頭開始輪詢纽匙;這種方法是非常笨而且也非常浪費資源务蝠,因為大部分客戶端是沒有I/O操作,我們也要去檢查烛缔;而Selector就不一樣了馏段,它在內(nèi)部可以同時管理多個I/O,當一個信道有I/O操作的時候践瓷,他會通知Selector院喜,Selector就是記住這個信道有I/O操作,并且知道是何種I/O操作晕翠,是讀呢喷舀?是寫呢?還是接受新的連接淋肾;所以如果使用Selector硫麻,它返回的結果只有兩種結果,一種是0樊卓,即在你調(diào)用的時刻沒有任何客戶端需要I/O操作拿愧,另一種結果是一組需要I/O操作的客戶端,這是你就根本不需要再檢查了碌尔,因為它返回給你的肯定是你想要的浇辜。這樣一種通知的方式比那種主動輪詢的方式要高效得多!
要使用選擇器(Selector)唾戚,需要創(chuàng)建一個Selector實例(使用靜態(tài)工廠方法open())并將其注冊(register)到想要監(jiān)控的信道上(注意柳洋,這要通過channel的方法實現(xiàn),而不是使用selector的方法)颈走。最后膳灶,調(diào)用選擇器的select()方法。該方法會阻塞等待立由,直到有一個或更多的信道準備好了I/O操作或等待超時轧钓。select()方法將返回可進行I/O操作的信道數(shù)量。現(xiàn)在锐膜,在一個單獨的線程中毕箍,通過調(diào)用select()方法就能檢查多個信道是否準備好進行I/O操作。如果經(jīng)過一段時間后仍然沒有信道準備好道盏,select()方法就會返回0而柑,并允許程序繼續(xù)執(zhí)行其他任務文捶。
下面將上面的TCP服務端代碼改寫成NIO的方式(案例5):
public class ServerConnect
{
private static final int BUF_SIZE=1024;
private static final int PORT = 8080;
private static final int TIMEOUT = 3000;
public static void main(String[] args)
{
selector();
}
public static void handleAccept(SelectionKey key) throws IOException{
ServerSocketChannel ssChannel = (ServerSocketChannel)key.channel();
SocketChannel sc = ssChannel.accept();
sc.configureBlocking(false);
sc.register(key.selector(), SelectionKey.OP_READ,ByteBuffer.allocateDirect(BUF_SIZE));
}
public static void handleRead(SelectionKey key) throws IOException{
SocketChannel sc = (SocketChannel)key.channel();
ByteBuffer buf = (ByteBuffer)key.attachment();
long bytesRead = sc.read(buf);
while(bytesRead>0){
buf.flip();
while(buf.hasRemaining()){
System.out.print((char)buf.get());
}
System.out.println();
buf.clear();
bytesRead = sc.read(buf);
}
if(bytesRead == -1){
sc.close();
}
}
public static void handleWrite(SelectionKey key) throws IOException{
ByteBuffer buf = (ByteBuffer)key.attachment();
buf.flip();
SocketChannel sc = (SocketChannel) key.channel();
while(buf.hasRemaining()){
sc.write(buf);
}
buf.compact();
}
public static void selector() {
Selector selector = null;
ServerSocketChannel ssc = null;
try{
selector = Selector.open();
ssc= ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(PORT));
ssc.configureBlocking(false);
ssc.register(selector, SelectionKey.OP_ACCEPT);
while(true){
if(selector.select(TIMEOUT) == 0){
System.out.println("==");
continue;
}
Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
while(iter.hasNext()){
SelectionKey key = iter.next();
if(key.isAcceptable()){
handleAccept(key);
}
if(key.isReadable()){
handleRead(key);
}
if(key.isWritable() && key.isValid()){
handleWrite(key);
}
if(key.isConnectable()){
System.out.println("isConnectable = true");
}
iter.remove();
}
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(selector!=null){
selector.close();
}
if(ssc!=null){
ssc.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
下面來慢慢講解這段代碼。
ServerSocketChannel
打開ServerSocketChannel:
`ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();`
關閉ServerSocketChannel:
`serverSocketChannel.close();`
監(jiān)聽新進來的連接:
`while``(``true``){`
`SocketChannel socketChannel = serverSocketChannel.accept();`
`}`
ServerSocketChannel可以設置成非阻塞模式媒咳。在非阻塞模式下粹排,accept() 方法會立刻返回,如果還沒有新進來的連接,返回的將是null涩澡。 因此顽耳,需要檢查返回的SocketChannel是否是null.如:
`ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();`
`serverSocketChannel.socket().bind(``new` `InetSocketAddress(``9999``));`
`serverSocketChannel.configureBlocking(``false``);`
`while` `(``true``)`
`{`
`SocketChannel socketChannel = serverSocketChannel.accept();`
`if` `(socketChannel !=` `null``)`
`{`
`// do something with socketChannel...`
`}`
`}`
Selector
Selector的創(chuàng)建:Selector selector = Selector.open();
為了將Channel和Selector配合使用,必須將Channel注冊到Selector上妙同,通過SelectableChannel.register()方法來實現(xiàn)射富,沿用案例5中的部分代碼:
`ssc= ServerSocketChannel.open();`
`ssc.socket().bind(``new` `InetSocketAddress(PORT));`
`ssc.configureBlocking(``false``);`
`ssc.register(selector, SelectionKey.OP_ACCEPT);`
與Selector一起使用時,Channel必須處于非阻塞模式下粥帚。這意味著不能將FileChannel與Selector一起使用胰耗,因為FileChannel不能切換到非阻塞模式。而套接字通道都可以芒涡。
注意register()方法的第二個參數(shù)柴灯。這是一個“interest集合”,意思是在通過Selector監(jiān)聽Channel時對什么事件感興趣费尽〕诨保可以監(jiān)聽四種不同類型的事件:
`1``. Connect`
`2``. Accept`
`3``. Read`
`4``. Write`
通道觸發(fā)了一個事件意思是該事件已經(jīng)就緒。所以依啰,某個channel成功連接到另一個服務器稱為“連接就緒”乎串。一個server socket channel準備好接收新進入的連接稱為“接收就緒”。一個有數(shù)據(jù)可讀的通道可以說是“讀就緒”速警。等待寫數(shù)據(jù)的通道可以說是“寫就緒”叹誉。
這四種事件用SelectionKey的四個常量來表示:
`1``. SelectionKey.OP_CONNECT`
`2``. SelectionKey.OP_ACCEPT`
`3``. SelectionKey.OP_READ`
`4``. SelectionKey.OP_WRITE`
SelectionKey
當向Selector注冊Channel時,register()方法會返回一個SelectionKey對象闷旧。這個對象包含了一些你感興趣的屬性:
interest集合
ready集合
Channel
Selector
附加的對象(可選)
interest集合:就像向Selector注冊通道一節(jié)中所描述的长豁,interest集合是你所選擇的感興趣的事件集合∶ψ疲可以通過SelectionKey讀寫interest集合匠襟。
ready 集合是通道已經(jīng)準備就緒的操作的集合。在一次選擇(Selection)之后该园,你會首先訪問這個ready set酸舍。Selection將在下一小節(jié)進行解釋±锍酰可以這樣訪問ready集合:
int readySet = selectionKey.readyOps();
可以用像檢測interest集合那樣的方法啃勉,來檢測channel中什么事件或操作已經(jīng)就緒。但是双妨,也可以使用以下四個方法淮阐,它們都會返回一個布爾類型:
selectionKey.isAcceptable();
selectionKey.isConnectable();
selectionKey.isReadable();
selectionKey.isWritable();
從SelectionKey訪問Channel和Selector很簡單叮阅。如下:
Channel channel = selectionKey.channel();
Selector selector = selectionKey.selector();
可以將一個對象或者更多信息附著到SelectionKey上,這樣就能方便的識別某個給定的通道泣特。例如浩姥,可以附加 與通道一起使用的Buffer,或是包含聚集數(shù)據(jù)的某個對象状您。使用方法如下:
selectionKey.attach(theObject);
Object attachedObj = selectionKey.attachment();
還可以在用register()方法向Selector注冊Channel的時候附加對象及刻。如:
SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);
通過Selector選擇通道
一旦向Selector注冊了一或多個通道,就可以調(diào)用幾個重載的select()方法竞阐。這些方法返回你所感興趣的事件(如連接、接受暑劝、讀或寫)已經(jīng)準備就緒的那些通道骆莹。換句話說,如果你對“讀就緒”的通道感興趣担猛,select()方法會返回讀事件已經(jīng)就緒的那些通道幕垦。
下面是select()方法:
- int select()
- int select(long timeout)
- int selectNow()
select()阻塞到至少有一個通道在你注冊的事件上就緒了。
select(long timeout)和select()一樣傅联,除了最長會阻塞timeout毫秒(參數(shù))先改。
selectNow()不會阻塞,不管什么通道就緒都立刻返回(譯者注:此方法執(zhí)行非阻塞的選擇操作蒸走。如果自從前一次選擇操作后仇奶,沒有通道變成可選擇的,則此方法直接返回零比驻。)该溯。
select()方法返回的int值表示有多少通道已經(jīng)就緒。亦即别惦,自上次調(diào)用select()方法后有多少通道變成就緒狀態(tài)狈茉。如果調(diào)用select()方法,因為有一個通道變成就緒狀態(tài)掸掸,返回了1氯庆,若再次調(diào)用select()方法,如果另一個通道就緒了扰付,它會再次返回1堤撵。如果對第一個就緒的channel沒有做任何操作,現(xiàn)在就有兩個就緒的通道羽莺,但在每次select()方法調(diào)用之間粒督,只有一個通道就緒了。
一旦調(diào)用了select()方法禽翼,并且返回值表明有一個或更多個通道就緒了屠橄,然后可以通過調(diào)用selector的selectedKeys()方法族跛,訪問“已選擇鍵集(selected key set)”中的就緒通道。如下所示:
Set selectedKeys = selector.selectedKeys();
當像Selector注冊Channel時锐墙,Channel.register()方法會返回一個SelectionKey 對象礁哄。這個對象代表了注冊到該Selector的通道∠保可以通過SelectionKey的selectedKeySet()方法訪問這些對象桐绒。
注意每次迭代末尾的keyIterator.remove()調(diào)用。Selector不會自己從已選擇鍵集中移除SelectionKey實例之拨。必須在處理完通道時自己移除茉继。下次該通道變成就緒時,Selector會再次將其放入已選擇鍵集中蚀乔。
SelectionKey.channel()方法返回的通道需要轉型成你要處理的類型烁竭,如ServerSocketChannel或SocketChannel等。
一個完整的使用Selector和ServerSocketChannel的案例可以參考案例5的selector()方法吉挣。
內(nèi)存映射文件
JAVA處理大文件派撕,一般用BufferedReader,BufferedInputStream這類帶緩沖的IO類,不過如果文件超大的話睬魂,更快的方式是采用MappedByteBuffer终吼。
MappedByteBuffer是NIO引入的文件內(nèi)存映射方案,讀寫性能極高氯哮。NIO最主要的就是實現(xiàn)了對異步操作的支持际跪。其中一種通過把一個套接字通道(SocketChannel)注冊到一個選擇器(Selector)中,不時調(diào)用后者的選擇(select)方法就能返回滿足的選擇鍵(SelectionKey),鍵中包含了SOCKET事件信息。這就是select模型喉钢。
SocketChannel的讀寫是通過一個類叫ByteBuffer來操作的.這個類本身的設計是不錯的,比直接操作byte[]方便多了. ByteBuffer有兩種模式:直接/間接.間接模式最典型(也只有這么一種)的就是HeapByteBuffer,即操作堆內(nèi)存 (byte[]).但是內(nèi)存畢竟有限,如果我要發(fā)送一個1G的文件怎么辦?不可能真的去分配1G的內(nèi)存.這時就必須使用”直接”模式,即 MappedByteBuffer,文件映射.
先中斷一下,談談操作系統(tǒng)的內(nèi)存管理.一般操作系統(tǒng)的內(nèi)存分兩部分:物理內(nèi)存;虛擬內(nèi)存.虛擬內(nèi)存一般使用的是頁面映像文件,即硬盤中的某個(某些)特殊的文件.操作系統(tǒng)負責頁面文件內(nèi)容的讀寫,這個過程叫”頁面中斷/切換”. MappedByteBuffer也是類似的,你可以把整個文件(不管文件有多大)看成是一個ByteBuffer.MappedByteBuffer 只是一種特殊的ByteBuffer垫卤,即是ByteBuffer的子類。 MappedByteBuffer 將文件直接映射到內(nèi)存(這里的內(nèi)存指的是虛擬內(nèi)存出牧,并不是物理內(nèi)存)穴肘。通常,可以映射整個文件舔痕,如果文件比較大的話可以分段進行映射评抚,只要指定文件的那個部分就可以。
概念
FileChannel提供了map方法來把文件影射為內(nèi)存映像文件: MappedByteBuffer map(int mode,long position,long size); 可以把文件的從position開始的size大小的區(qū)域映射為內(nèi)存映像文件伯复,mode指出了 可訪問該內(nèi)存映像文件的方式:
- READ_ONLY,(只讀): 試圖修改得到的緩沖區(qū)將導致拋出 ReadOnlyBufferException.(MapMode.READ_ONLY)
- READ_WRITE(讀/寫): 對得到的緩沖區(qū)的更改最終將傳播到文件慨代;該更改對映射到同一文件的其他程序不一定是可見的。 (MapMode.READ_WRITE)
- PRIVATE(專用): 對得到的緩沖區(qū)的更改不會傳播到文件啸如,并且該更改對映射到同一文件的其他程序也不是可見的侍匙;相反,會創(chuàng)建緩沖區(qū)已修改部分的專用副本叮雳。 (MapMode.PRIVATE)
MappedByteBuffer是ByteBuffer的子類想暗,其擴充了三個方法:
- force():緩沖區(qū)是READ_WRITE模式下妇汗,此方法對緩沖區(qū)內(nèi)容的修改強行寫入文件;
- load():將緩沖區(qū)的內(nèi)容載入內(nèi)存说莫,并返回該緩沖區(qū)的引用杨箭;
- isLoaded():如果緩沖區(qū)的內(nèi)容在物理內(nèi)存中,則返回真储狭,否則返回假互婿;
案例對比
這里通過采用ByteBuffer和MappedByteBuffer分別讀取大小約為5M的文件”src/1.ppt”來比較兩者之間的區(qū)別,method3()是采用MappedByteBuffer讀取的辽狈,method4()對應的是ByteBuffer慈参。
public static void method4(){
RandomAccessFile aFile = null;
FileChannel fc = null;
try{
aFile = new RandomAccessFile("src/1.ppt","rw");
fc = aFile.getChannel();
long timeBegin = System.currentTimeMillis();
ByteBuffer buff = ByteBuffer.allocate((int) aFile.length());
buff.clear();
fc.read(buff);
//System.out.println((char)buff.get((int)(aFile.length()/2-1)));
//System.out.println((char)buff.get((int)(aFile.length()/2)));
//System.out.println((char)buff.get((int)(aFile.length()/2)+1));
long timeEnd = System.currentTimeMillis();
System.out.println("Read time: "+(timeEnd-timeBegin)+"ms");
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(aFile!=null){
aFile.close();
}
if(fc!=null){
fc.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
public static void method3(){
RandomAccessFile aFile = null;
FileChannel fc = null;
try{
aFile = new RandomAccessFile("src/1.ppt","rw");
fc = aFile.getChannel();
long timeBegin = System.currentTimeMillis();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, aFile.length());
// System.out.println((char)mbb.get((int)(aFile.length()/2-1)));
// System.out.println((char)mbb.get((int)(aFile.length()/2)));
//System.out.println((char)mbb.get((int)(aFile.length()/2)+1));
long timeEnd = System.currentTimeMillis();
System.out.println("Read time: "+(timeEnd-timeBegin)+"ms");
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(aFile!=null){
aFile.close();
}
if(fc!=null){
fc.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
通過在入口函數(shù)main()中運行:
method3();
System.out.println("=============");
method4();
輸出結果(運行在普通PC機上):
Read time: 2ms
=============
Read time: 12ms
通過輸出結果可以看出彼此的差別,一個例子也許是偶然刮萌,那么下面把5M大小的文件替換為200M的文件驮配,輸出結果:
Read time: 1ms
=============
Read time: 407ms
可以看到差距拉大。
注:MappedByteBuffer有資源釋放的問題:被MappedByteBuffer打開的文件只有在垃圾收集時才會被關閉尊勿,而這個點是不確定的。在Javadoc中這里描述:A mapped byte buffer and the file mapping that it represents remian valid until the buffer itself is garbage-collected畜侦。詳細可以翻閱參考資料5和6.
其余功能介紹
看完以上陳述元扔,詳細大家對NIO有了一定的了解,下面主要通過幾個案例旋膳,來說明NIO的其余功能澎语,下面代碼量偏多,功能性講述偏少验懊。
Scatter/Gatter
分散(scatter)從Channel中讀取是指在讀操作時將讀取的數(shù)據(jù)寫入多個buffer中擅羞。因此,Channel將從Channel中讀取的數(shù)據(jù)“分散(scatter)”到多個Buffer中义图。
聚集(gather)寫入Channel是指在寫操作時將多個buffer的數(shù)據(jù)寫入同一個Channel减俏,因此,Channel 將多個Buffer中的數(shù)據(jù)“聚集(gather)”后發(fā)送到Channel碱工。
scatter / gather經(jīng)常用于需要將傳輸?shù)臄?shù)據(jù)分開處理的場合娃承,例如傳輸一個由消息頭和消息體組成的消息,你可能會將消息體和消息頭分散到不同的buffer中怕篷,這樣你可以方便的處理消息頭和消息體历筝。
案例:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.FileChannel;
public class ScattingAndGather
{
public static void main(String args[]){
gather();
}
public static void gather()
{
ByteBuffer header = ByteBuffer.allocate(10);
ByteBuffer body = ByteBuffer.allocate(10);
byte [] b1 = {'0', '1'};
byte [] b2 = {'2', '3'};
header.put(b1);
body.put(b2);
ByteBuffer [] buffs = {header, body};
try
{
FileOutputStream os = new FileOutputStream("src/scattingAndGather.txt");
FileChannel channel = os.getChannel();
channel.write(buffs);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
transferFrom & transferTo
FileChannel的transferFrom()方法可以將數(shù)據(jù)從源通道傳輸?shù)紽ileChannel中。
public static void method1(){
RandomAccessFile fromFile = null;
RandomAccessFile toFile = null;
try
{
fromFile = new RandomAccessFile("src/fromFile.xml","rw");
FileChannel fromChannel = fromFile.getChannel();
toFile = new RandomAccessFile("src/toFile.txt","rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
System.out.println(count);
toChannel.transferFrom(fromChannel, position, count);
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
try{
if(fromFile != null){
fromFile.close();
}
if(toFile != null){
toFile.close();
}
}
catch(IOException e){
e.printStackTrace();
}
}
}
方法的輸入?yún)?shù)position表示從position處開始向目標文件寫入數(shù)據(jù)廊谓,count表示最多傳輸?shù)淖止?jié)數(shù)梳猪。如果源通道的剩余空間小于 count 個字節(jié),則所傳輸?shù)淖止?jié)數(shù)要小于請求的字節(jié)數(shù)蒸痹。此外要注意春弥,在SoketChannel的實現(xiàn)中呛哟,SocketChannel只會傳輸此刻準備好的數(shù)據(jù)(可能不足count字節(jié))。因此惕稻,SocketChannel可能不會將請求的所有數(shù)據(jù)(count個字節(jié))全部傳輸?shù)紽ileChannel中竖共。
transferTo()方法將數(shù)據(jù)從FileChannel傳輸?shù)狡渌腸hannel中。
public static void method2()
{
RandomAccessFile fromFile = null;
RandomAccessFile toFile = null;
try
{
fromFile = new RandomAccessFile("src/fromFile.txt","rw");
FileChannel fromChannel = fromFile.getChannel();
toFile = new RandomAccessFile("src/toFile.txt","rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
System.out.println(count);
fromChannel.transferTo(position, count,toChannel);
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
try{
if(fromFile != null){
fromFile.close();
}
if(toFile != null){
toFile.close();
}
}
catch(IOException e){
e.printStackTrace();
}
}
}
上面所說的關于SocketChannel的問題在transferTo()方法中同樣存在俺祠。SocketChannel會一直傳輸數(shù)據(jù)直到目標buffer被填滿公给。
Pipe
Java NIO 管道是2個線程之間的單向數(shù)據(jù)連接。Pipe有一個source通道和一個sink通道蜘渣。數(shù)據(jù)會被寫到sink通道淌铐,從source通道讀取。
public static void method1(){
Pipe pipe = null;
ExecutorService exec = Executors.newFixedThreadPool(2);
try{
pipe = Pipe.open();
final Pipe pipeTemp = pipe;
exec.submit(new Callable<Object>(){
@Override
public Object call() throws Exception
{
Pipe.SinkChannel sinkChannel = pipeTemp.sink();//向通道中寫數(shù)據(jù)
while(true){
TimeUnit.SECONDS.sleep(1);
String newData = "Pipe Test At Time "+System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()){
System.out.println(buf);
sinkChannel.write(buf);
}
}
}
});
exec.submit(new Callable<Object>(){
@Override
public Object call() throws Exception
{
Pipe.SourceChannel sourceChannel = pipeTemp.source();//向通道中讀數(shù)據(jù)
while(true){
TimeUnit.SECONDS.sleep(1);
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.clear();
int bytesRead = sourceChannel.read(buf);
System.out.println("bytesRead="+bytesRead);
while(bytesRead >0 ){
buf.flip();
byte b[] = new byte[bytesRead];
int i=0;
while(buf.hasRemaining()){
b[i]=buf.get();
System.out.printf("%X",b[i]);
i++;
}
String s = new String(b);
System.out.println("=================||"+s);
bytesRead = sourceChannel.read(buf);
}
}
}
});
}catch(IOException e){
e.printStackTrace();
}finally{
exec.shutdown();
}
}
DatagramChannel
Java NIO中的DatagramChannel是一個能收發(fā)UDP包的通道蔫缸。因為UDP是無連接的網(wǎng)絡協(xié)議腿准,所以不能像其它通道那樣讀取和寫入。它發(fā)送和接收的是數(shù)據(jù)包拾碌。
public static void reveive(){
DatagramChannel channel = null;
try{
channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(8888));
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.clear();
channel.receive(buf);
buf.flip();
while(buf.hasRemaining()){
System.out.print((char)buf.get());
}
System.out.println();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(channel!=null){
channel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
public static void send(){
DatagramChannel channel = null;
try{
channel = DatagramChannel.open();
String info = "I'm the Sender!";
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.clear();
buf.put(info.getBytes());
buf.flip();
int bytesSent = channel.send(buf, new InetSocketAddress("10.10.195.115",8888));
System.out.println(bytesSent);
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(channel!=null){
channel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
可以通過閱讀參考資料2和3了解更多的NIO細節(jié)知識吐葱,前人栽樹后人乘涼,這里就不贅述啦校翔。
參考資料
- Java NIO
- Java NIO 系列教程
-
Java NIO 詳解
4. 《深入分析Java Web技術內(nèi)幕》許令波 著 - java大文件讀寫操作弟跑,java nio 之MappedByteBuffer,高效文件/內(nèi)存映射
- java nio 之MappedByteBuffer防症,高效文件/內(nèi)存映射
相關文章
- Java NIO系列教程(12):Java NIO與IO
- Java NIO系列教程(11):Pipe
- Java NIO系列教程(10):Java NIO DatagramChannel
- Java NIO系列教程(9):ServerSocketChannel
- Java NIO系列教程(8):SocketChannel
- Java NIO系列教程(7):FileChannel
- Java NIO系列教程(6):Selector
- Java NIO系列教程(5):通道之間的數(shù)據(jù)傳輸
- Java NIO系列教程(4):Scatter/Gather
- Java NIO系列教程(3) :Buffer