Posted on 2011-12-19 11:26
cooperzh 閱讀(270)
評(píng)論(0) 編輯 收藏 所屬分類(lèi):
NIO
channel 用于在 ByteBuffer 和socket(或文件)之間傳輸數(shù)據(jù)
channel的實(shí)現(xiàn)經(jīng)常使用操作系統(tǒng)的本地代碼
implement InterruptibleChannel 后標(biāo)示該通道可以被中斷,大多數(shù)channel都是可以被中斷的
面向字節(jié)的接口:ReadableByteChannel,WriteableByteChannel
ByteChannel接口繼承了ReadableByteChannel和WriteableByteChannel接口
IO廣義上可以分為file IO 和 stream IO,對(duì)應(yīng)file通道和socket通道
file通道的類(lèi):FileChanel
socket通道的類(lèi):SocketChannel,ServerSocketChannel,DatagramChanenel
FileChannel不能直接創(chuàng)建,只能通過(guò)打開(kāi)的RandomAccessFile,FileInputStream,FileOutputStream調(diào)用getChannel()獲得
socket通道可以直接調(diào)用其工廠方法獲得實(shí)例
只實(shí)現(xiàn)ReadableByteChannel或WriteableByteChannel的通道都是單向的,兩個(gè)都實(shí)現(xiàn)就是雙向的
實(shí)現(xiàn)ByteChannel的通道都是雙向的
所有socketChannel類(lèi)都是雙向的
read() 將字節(jié)從通道讀入緩沖區(qū)
write() 將字節(jié)從緩沖區(qū)寫(xiě)入通道
講byteBuffer的數(shù)據(jù)寫(xiě)入通道:
while(buffer.hasRemaining()){
dest.write(buffer);
}
因?yàn)閣rite操作可能會(huì)因?yàn)槠渌€程的調(diào)用而阻塞
緩沖區(qū)可以重復(fù)使用,而通道是一次性的,用完就關(guān)閉。通道關(guān)閉后,代表的與socket的連接會(huì)丟失
close方法是阻塞式的,多次close沒(méi)有壞處。close的實(shí)現(xiàn)取決于操作系統(tǒng)。
實(shí)現(xiàn)InterruptibleChannel接口的類(lèi),如果線程在該通道上被阻塞,同時(shí)線程被中斷,則通道將會(huì)關(guān)閉,阻塞線程會(huì)報(bào)異常:ClosedByInterruptException.
另外,設(shè)置了interrupt status的線訪問(wèn)一個(gè)通道時(shí),該通道將會(huì)立即被關(guān)閉,同時(shí)拋出ClosedByInterruptException異常
而線程的interrupt status是線程的interrupt()方法設(shè)置,并通過(guò)Thread.interrupted()清除。
通道上的線程休眠,則通道會(huì)關(guān)閉
當(dāng)一個(gè)通道被關(guān)閉的時(shí)候,所有在此通道上休眠的線程都將被喚醒,并收到一個(gè)AsynchronousCloseException,接著通道被關(guān)閉。
一個(gè)通道同時(shí)對(duì)多個(gè)byteBuffer的操作稱(chēng)為分散和聚合
Scatter分散體現(xiàn)在channel.read(ByteBuffer[] dsts) 和 channel.read(ByteBuffer[] dsts,int offset,int length);
Gather分散體現(xiàn)在channel.write(ByteBuffer[] dsts) 和 channel.write(ByteBuffer[] dsts,int offset,int length);
offset 和 length指的是ByteBuffer[]中第幾個(gè)ByteBuffer