Java中channel用法總結(jié)
本文實(shí)例總結(jié)了Java中channel用法。分享給大家供大家參考。具體分析如下:
1.Channel接口的定義:
public interface Channel { public boolean isOpen( ); public void close( ) throws IOException; }
2.Channel的常見(jiàn)類型:
FileChannel, SocketChannel, ServerSocketChannel, and DatagramChannel;
FileChannel通過(guò)RandomAccessFile, FileInputStream, FileOutputStream的getChannel()來(lái)初始化。
SocketChannel sc = SocketChannel.open(); sc.connect (new InetSocketAddress ("somehost", someport)); ServerSocketChannel ssc = ServerSocketChannel.open( ); ssc.socket().bind (new InetSocketAddress (somelocalport)); DatagramChannel dc = DatagramChannel.open();
3.Scatter/Gather,必須使用ByteBuffer.allocateDirect(100)
public interface ScatteringByteChannel extends ReadableByteChannel { public long read (ByteBuffer [] dsts) throws IOException; public long read (ByteBuffer [] dsts, int offset, int length) throws IOException; } public interface GatheringByteChannel extends WritableByteChannel { public long write(ByteBuffer[] srcs) throws IOException; public long write(ByteBuffer[] srcs, int offset, int length) throws IOException; }
4.file lock是和file相關(guān),而不是channel??梢詫?duì)進(jìn)程有效,而不是線程??梢酝ㄟ^(guò)內(nèi)存映射文件(memory-mapped file)來(lái)實(shí)現(xiàn)線程同步
5.buffer = fileChannel.map (FileChannel.MapMode.READ_ONLY, 100, 200);
6.MappedByteBuffer are direct. load( )將整個(gè)文件加載到內(nèi)存(改方法不能保證完成)。force( )將數(shù)據(jù)flush到硬盤。
7.未綁定端口的DatagramChannel系統(tǒng)會(huì)自動(dòng)分配端口。DatagramChannel的connect(),將保證只接受指定源地址的數(shù)據(jù)包。這時(shí)候,可以使用普通的read和write方法,包括Scatter/Gather
希望本文所述對(duì)大家的java程序設(shè)計(jì)有所幫助。
相關(guān)文章
淺談Java自定義類加載器及JVM自帶的類加載器之間的交互關(guān)系
這篇文章主要介紹了淺談Java自定義類加載器及JVM自帶的類加載器之間的交互關(guān)系,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02Spring中事務(wù)管理方案和事務(wù)管理器及事務(wù)控制的API詳解
這篇文章主要介紹了Spring中事務(wù)管理方案和事務(wù)管理器及事務(wù)控制的API詳解,事務(wù)管理是指對(duì)事務(wù)進(jìn)行管理和控制,以確保事務(wù)的正確性和完整性,事務(wù)管理的作用是保證數(shù)據(jù)庫(kù)的數(shù)據(jù)操作的一致性和可靠性,需要的朋友可以參考下2023-08-08淺析Java中Map與HashMap,Hashtable,HashSet的區(qū)別
HashMap和Hashtable兩個(gè)類都實(shí)現(xiàn)了Map接口,二者保存K-V對(duì)(key-value對(duì));HashSet則實(shí)現(xiàn)了Set接口,性質(zhì)類似于集合2013-09-09Java編寫時(shí)間工具類ZTDateTimeUtil的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用Java編寫時(shí)間工具類ZTDateTimeUtil,文中的示例代碼講解詳細(xì),有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11淺談如何在項(xiàng)目中使用Spring Cloud Alibaba Sentinel組件
隨著微服務(wù)的流行,服務(wù)和服務(wù)之間的穩(wěn)定性變得越來(lái)越重要。本文主要介紹了使用Spring Cloud Alibaba Sentinel組件,感興趣的可以了解一下2021-07-07SpringBootTest單元測(cè)試報(bào)錯(cuò)的解決方案
這篇文章主要介紹了SpringBootTest單元測(cè)試報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09