万字长文:助你攻破 JAVA NIO 技术壁垒
本文来源:https://honeypps.com/java/java-nio-quick-start/
概述
Channel
FileChannel DatagramChannel SocketChannel ServerSocketChannel
Buffer
Selector
FileChannel
传统IO vs NIO
public static void method2(){ |
public static void method1(){ |
Buffer的使用
分配空间(ByteBuffer buf = ByteBuffer.allocate(1024); 还有一种allocateDirector后面再陈述) 写入数据到Buffer(int bytesRead = fileChannel.read(buf);) 调用filp()方法( buf.flip();) 从Buffer中读取数据(System.out.print((char)buf.get());) 调用clear()方法或者compact()方法

从Channel写到Buffer (fileChannel.read(buf)) 通过Buffer的put()方法 (buf.put(…))
从Buffer读取到Channel (channel.write(buf)) 使用get()方法从Buffer中读取数据 (buf.get())



SocketChannel
channel.configureBlocking(false) |
public static void client(){ |
服务端代码(案例4):
public static void server(){ |
输出结果:(略)
根据案例分析,总结一下SocketChannel的用法。
打开SocketChannel:
socketChannel = SocketChannel.open(); |
关闭:
socketChannel.close(); |
读取数据:
String info = "I'm "+i+++"-th information from client"; |
TCP服务端的NIO写法
public class ServerConnect |
下面来慢慢讲解这段代码。
ServerSocketChannel
打开ServerSocketChannel:
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); |
关闭ServerSocketChannel:
serverSocketChannel.close(); |
监听新进来的连接:
while(true){ |
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); |
Selector
ssc= ServerSocketChannel.open(); |
1. Connect
2. Accept
3. Read
4. Write1. SelectionKey.OP_CONNECT
2. SelectionKey.OP_ACCEPT
3. SelectionKey.OP_READ
4. SelectionKey.OP_WRITESelectionKey
interest集合 ready集合 Channel Selector 附加的对象(可选)
int readySet = selectionKey.readyOps(); |
selectionKey.isAcceptable(); |
从SelectionKey访问Channel和Selector很简单。如下:
Channel channel = selectionKey.channel(); |
selectionKey.attach(theObject); |
还可以在用register()方法向Selector注册Channel的时候附加对象。如:
SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject); |
通过Selector选择通道
int select() int select(long timeout) int selectNow()
Set selectedKeys = selector.selectedKeys(); |
内存映射文件
概念
READ_ONLY,(只读):试图修改得到的缓冲区将导致抛出 ReadOnlyBufferException.(MapMode.READ_ONLY) READ_WRITE(读/写):对得到的缓冲区的更改最终将传播到文件;该更改对映射到同一文件的其他程序不一定是可见的。(MapMode.READ_WRITE) PRIVATE(专用):对得到的缓冲区的更改不会传播到文件,并且该更改对映射到同一文件的其他程序也不是可见的;相反,会创建缓冲区已修改部分的专用副本。(MapMode.PRIVATE)
force():缓冲区是READ_WRITE模式下,此方法对缓冲区内容的修改强行写入文件; load():将缓冲区的内容载入内存,并返回该缓冲区的引用; isLoaded():如果缓冲区的内容在物理内存中,则返回真,否则返回假;
案例对比
public static void method4(){ |
通过在入口函数main()中运行:
method3(); |
输出结果(运行在普通PC机上):
Read time: 2ms |
Read time: 1ms |
注: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.
其余功能介绍
Scatter/Gatter
import java.io.File; |
###transferFrom & transferTo
FileChannel的transferFrom()方法可以将数据从源通道传输到FileChannel中。
public static void method1(){ |
public static void method2() |
Pipe
public static void method1(){ |
DatagramChannel
public static void reveive(){ |
特别推荐一个分享架构+算法的优质内容,还没关注的小伙伴,可以长按关注一下:

长按订阅更多精彩▼
如有收获,点个在看,诚挚感谢


