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