posts - 12, comments - 0, trackbacks - 0, articles - 7
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          NIO channel

          Posted on 2011-12-19 11:26 cooperzh 閱讀(271) 評論(0)  編輯  收藏 所屬分類: NIO
          channel 用于在 ByteBuffer 和socket(或文件)之間傳輸數(shù)據(jù)

          channel的實現(xiàn)經(jīng)常使用操作系統(tǒng)的本地代碼

          implement InterruptibleChannel 后標(biāo)示該通道可以被中斷,大多數(shù)channel都是可以被中斷的
          面向字節(jié)的接口:ReadableByteChannel,WriteableByteChannel
          ByteChannel接口繼承了ReadableByteChannel和WriteableByteChannel接口

          IO廣義上可以分為file IO 和 stream IO,對應(yīng)file通道和socket通道
          file通道的類:FileChanel
          socket通道的類:SocketChannel,ServerSocketChannel,DatagramChanenel

          FileChannel不能直接創(chuàng)建,只能通過打開的RandomAccessFile,FileInputStream,FileOutputStream調(diào)用getChannel()獲得
          socket通道可以直接調(diào)用其工廠方法獲得實例

          只實現(xiàn)ReadableByteChannel或WriteableByteChannel的通道都是單向的,兩個都實現(xiàn)就是雙向的
          實現(xiàn)ByteChannel的通道都是雙向的

          所有socketChannel類都是雙向的

          read() 將字節(jié)從通道讀入緩沖區(qū)
          write() 將字節(jié)從緩沖區(qū)寫入通道

          講byteBuffer的數(shù)據(jù)寫入通道:
          while(buffer.hasRemaining()){
              dest.write(buffer);
          }
          因為write操作可能會因為其他線程的調(diào)用而阻塞

          緩沖區(qū)可以重復(fù)使用,而通道是一次性的,用完就關(guān)閉。通道關(guān)閉后,代表的與socket的連接會丟失

          close方法是阻塞式的,多次close沒有壞處。close的實現(xiàn)取決于操作系統(tǒng)。

          實現(xiàn)InterruptibleChannel接口的類,如果線程在該通道上被阻塞,同時線程被中斷,則通道將會關(guān)閉,阻塞線程會報異常:ClosedByInterruptException.

          另外,設(shè)置了interrupt status的線訪問一個通道時,該通道將會立即被關(guān)閉,同時拋出ClosedByInterruptException異常
          而線程的interrupt status是線程的interrupt()方法設(shè)置,并通過Thread.interrupted()清除。

          通道上的線程休眠,則通道會關(guān)閉

          當(dāng)一個通道被關(guān)閉的時候,所有在此通道上休眠的線程都將被喚醒,并收到一個AsynchronousCloseException,接著通道被關(guān)閉。

          一個通道同時對多個byteBuffer的操作稱為分散和聚合
          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[]中第幾個ByteBuffer



          主站蜘蛛池模板: 安溪县| 伽师县| 潜江市| 同德县| 台山市| 家居| 临夏县| 勃利县| 中卫市| 开鲁县| 宜宾市| 永善县| 旬邑县| 洪洞县| 神农架林区| 台东市| 托克托县| 大安市| 华安县| 龙井市| 唐海县| 双鸭山市| 绥滨县| 阿拉尔市| 水城县| 乐业县| 安乡县| 嘉兴市| 连山| 鄢陵县| 长武县| 多伦县| 湖南省| 成安县| 金门县| 曲靖市| 黄龙县| 东丽区| 汉沽区| 沧州市| 景宁|