华为二面!!!面试官直接问我Java中到底什么是NIO?这不是直接送分题?

先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以添加V获取:vip1024b (备注Java)
img

正文

通过非直接缓冲区,想要将数据写入到物理磁盘中,或者是从物理磁盘读取数据。都需要经过JVM和操作系统,数据在两个地址空间中传输时,会copy一份保存在对方的空间中。所以费直接缓冲区的读取效率较低.。

image

直接缓冲区


只有ByteBuffer可以获得直接缓冲区,通过allocateDirect()获取的缓冲区为直接缓冲区,这些缓冲区是建立在物理内存之中的。

public static ByteBuffer allocateDirect(int capacity) {

return new DirectByteBuffer(capacity);

}

DirectByteBuffer(int cap) { // package-private

// 申请物理内存

boolean pa = VM.isDirectMemoryPageAligned();

}

直接缓冲区通过在操作系统和JVM之间创建物理内存映射文件加快缓冲区数据读/写入物理磁盘的速度。放到物理内存映射文件中的数据就不归应用程序控制了,操作系统会自动将物理内存映射文件中的数据写入到物理内存中。

image

通道(Channel)

========================================================================

Channel由java.nio.channels 包定义的。Channel 表示IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过Channel 本身不能直接访问数据,Channel 只能与Buffer 进行交互

应用程序进行读写操作调用函数时,底层调用的操作系统提供给用户的读写API,调用这些API时会生成对应的指令,CPU则会执行这些指令。在计算机刚出现的那段时间,所有读写请求的指令都有CPU去执行,过多的读写请求会导致CPU无法去执行其他命令,从而CPU的利用率降低。

image

后来,DMA(Direct Memory Access,直接存储器访问)出现了。当IO请求传到计算机底层时,DMA会向CPU请求,让DMA去处理这些IO操作,从而可以让CPU去执行其他指令。DMA处理IO操作时,会请求获取总线的使用权。当IO请求过多时,会导致大量总线用于处理IO请求,从而降低效率

image

于是便有了Channel(通道),Channel相当于一个专门用于IO操作的独立处理器,它具有独立处理IO请求的能力,当有IO请求时,它会自行处理这些IO请求 。

image

Java Channel


image

  • 本地文件IO

  • FileChannel

  • 网络IO

  • SocketChanel、ServerSocketChannel:用于TCP传输

  • DatagramChannel:用于UDP传输

获得通道的方法

对象调用getChannel() 方法

获取通道的一种方式是对支持通道的对象调用getChannel() 方法。支持通道的类如下:

  • FileInputStream

  • FileOutputStream

  • RandomAccessFile

  • DatagramSocket

  • Socket

  • ServerSocket

例子:

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.net.DatagramSocket;

import java.net.ServerSocket;

import java.net.Socket;

import java.nio.channels.DatagramChannel;

import java.nio.channels.FileChannel;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.nio.file.Paths;

public class demo2 {

public static void main(String[] args) throws IOException {

// 本地通道

FileInputStream fileInputStream = new FileInputStream(“zwt”);

FileChannel channel1 = fileInputStream.getChannel();

FileOutputStream fileOutputStream = new FileOutputStream(“zwt”);

FileChannel channel2 = fileOutputStream.getChannel();

// 网络通道

Socket socket = new Socket();

SocketChannel channel3 = socket.getChannel();

ServerSocket serverSocket = new ServerSocket();

ServerSocketChannel channel4 = serverSocket.getChannel();

DatagramSocket datagramSocket = new DatagramSocket();

DatagramChannel channel5 = datagramSocket.getChannel();

// 最后要关闭通道

FileChannel open = FileChannel.open(Paths.get(“zwt”));

SocketChannel open1 = SocketChannel.open();

}

}

getChannel()+非直接缓冲区
  • getChannel()获得通道

  • allocate()获得非直接缓冲区

通过非直接缓冲区读写数据,需要通过通道来传输缓冲区里的数据

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class demo4 {

public static void main(String[] args) {

FileInputStream is = null;

FileOutputStream os = null;

// 获得通道

FileChannel inChannel = null;

FileChannel outChannel = null;

// 利用 try-catch-finally 保证关闭

try {

is = new FileInputStream(“”);

os = new FileOutputStream(“”);

// 获得通道

inChannel = is.getChannel();

outChannel = os.getChannel();

// 获得缓冲区,用于在通道中传输数据

ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

// 循环将字节数据放入到buffer中,然后写入磁盘中

while (inChannel.read(byteBuffer) != -1) {

// 切换模式

byteBuffer.flip();

outChannel.write(byteBuffer);

byteBuffer.clear();

}

} catch (IOException e) {

e.printStackTrace();

} finally {

if (inChannel != null) {

try {

inChannel.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (outChannel != null) {

try {

outChannel.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (is != null) {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (os != null) {

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

open()+直接缓冲区
  • 通过open获得通道

  • 通过FileChannel.map()获取直接缓冲区

使用直接缓冲区时,无需通过通道来传输数据,直接将数据放在缓冲区内即可

import java.io.IOException;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

public class demo5 {

public static void main(String[] args) throws IOException {

// 通过open()方法来获得通道

FileChannel inChannel = FileChannel.open(Paths.get(“”), StandardOpenOption.READ);

// outChannel需要为 READ WRITE CREATE模式

// READ WRITE是因为后面获取直接缓冲区时模式为READ_WRITE模式

// CREATE是因为要创建新的文件

FileChannel outChannel = FileChannel.open(Paths.get(“”), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

// 获得直接缓冲区

MappedByteBuffer inMapBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());

MappedByteBuffer outMapBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());

// 字节数组

byte[] bytes = new byte[inMapBuf.limit()];

// 因为是直接缓冲区,可以直接将数据放入到内存映射文件,无需通过通道传输

inMapBuf.get(bytes);

outMapBuf.put(bytes);

// 关闭缓冲区,这里没有用try-catch-finally

inChannel.close();

outChannel.close();

}

}

通道间直接传输

public static void channelToChannel() throws IOException {

long start = System.currentTimeMillis();

// 通过open()方法来获得通道

FileChannel inChannel = FileChannel.open(Paths.get(“”), StandardOpenOption.READ);

// outChannel需要为 READ WRITE CREATE模式

// READ WRITE是因为后面获取直接缓冲区时模式为READ_WRITE模式

// CREATE是因为要创建新的文件

FileChannel outChannel = FileChannel.open(Paths.get(“”), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

// 通道间直接传输

inChannel.transferTo(0, inChannel.size(), outChannel);

// 对应的还有transferFrom

// outChannel.transferFrom(inChannel, 0, inChannel.size());

inChannel.close();

outChannel.close();

}

直接缓冲区VS非直接缓冲区

// getChannel() + 非直接缓冲区耗时

708

// open() + 直接缓冲区耗时

115

// channel transferTo channel耗时

47

直接缓冲区的读写速度虽然很快,但是会占用很多很多内存空间。如果文件过大,会使得计算机运行速度变慢

分散和聚集


分散读取

分散读取(Scattering Reads)是指从Channel 中读取的数据“分散”到多个Buffer 中。

注意:按照缓冲区的顺序,从Channel 中读取的数据依次将 Buffer 填满。

聚集写入

聚集写入(Gathering Writes)是指将多个Buffer 中的数据“聚集”到Channel。

按照缓冲区的顺序,写入position 和limit 之间的数据到Channel。

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class demo6 {

public static void main(String[] args) throws IOException {

FileInputStream is = new FileInputStream(“”);

FileOutputStream os = new FileOutputStream(“”);

FileChannel inChannel = is.getChannel();

FileChannel outChannel = os.getChannel();

// 获得多个缓冲区,并且放入到缓冲区数组中

ByteBuffer byteBuffer1 = ByteBuffer.allocate(50);

ByteBuffer byteBuffer2 = ByteBuffer.allocate(1024);

ByteBuffer[] byteBuffers = {byteBuffer1, byteBuffer2};

// 分散读取

inChannel.read(byteBuffers);

byteBuffer1.flip();

byteBuffer2.flip();

// 聚集写入

outChannel.write(byteBuffers);

}

}

非阻塞式网络通信

=====================================================================

概念


底层原理可见:操作系统-文件IO

比喻:

举个你去饭堂吃饭的例⼦,你好⽐⽤户程序,饭堂好⽐操作系统。

阻塞 I/O 好⽐,

你去饭堂吃饭,但是饭堂的菜还没做好,然后你就⼀直在那⾥等啊等,

等了好⻓⼀段时间终于等到饭堂阿姨把菜端了出来(数据准备的过程),

但是你还得继续等阿姨把菜(内核空间)打到你的饭盒⾥(⽤户空间),

经历完这两个过程,你才可以离开。

⾮阻塞 I/O 好⽐,

你去了饭堂,问阿姨菜做好了没有,阿姨告诉你没,

你就离开了,过⼏⼗分钟,你⼜来,

饭堂问阿姨,阿姨说做好了,于是阿姨帮你把菜打到你的饭盒⾥,这个过程你是得等待的。

基于⾮阻塞的 I/O 多路复⽤好⽐,

你去饭堂吃饭,发现有⼀排窗⼝,饭堂阿姨告诉你这些窗⼝都还没做好菜,

等做好了再通知你,于是等啊等( select 调⽤中),过了⼀会阿姨通知你菜做好了,

但是不知道哪个窗⼝的菜做好了,你⾃⼰看吧。

于是你只能⼀个⼀个窗⼝去确认,后⾯发现 5 号窗⼝菜做好了,

于是你让 5 号窗⼝的阿姨帮你打菜到饭盒⾥,这个打菜的过程你是要等待的,虽然时间不⻓。

打完菜后,你⾃然就可以离开了。

异步 I/O 好⽐,

你让饭堂阿姨将菜做好并把菜打到饭盒⾥后,把饭盒送到你⾯前,整个过程你都不需要任何等待。

阻塞式网络通信


package NIOAndBIO;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

public class BIO {

public static void main(String[] args) throws IOException {

Thread thread1 = new Thread(() -> {

try {

server();

} catch (IOException e) {

e.printStackTrace();

}

});

Thread thread2 = new Thread(() -> {

try {

client();

} catch (IOException e) {

e.printStackTrace();

}

});

thread1.start();

thread2.start();

}

public static void client() throws IOException {

// 创建客户端通道

SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(“127.0.0.1”, 2022));

// 读取信息 D:\bizhi\bizhi202008\wallhaven-kwp2qq.jpg

FileChannel fileChannel = FileChannel.open(Paths.get(“D:\\bizhi\\bizhi202008\\wallhaven-kwp2qq.jpg”), StandardOpenOption.READ);

// 创建缓冲区

ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

// 写入数据

while (fileChannel.read(byteBuffer) != -1) {

byteBuffer.flip();

socketChannel.write(byteBuffer);

byteBuffer.clear();

}

fileChannel.close();

socketChannel.close();

}

public static void server() throws IOException {

// 创建服务端通道

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

FileChannel fileChannel = FileChannel.open(Paths.get(“D:\\bizhi\\bizhi202008\\wallhaven-kwp2qq.jpg”), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

// 绑定链接

serverSocketChannel.bind(new InetSocketAddress(2022));

// 获取客户端的通道

SocketChannel socketChannel = serverSocketChannel.accept();

// 创建缓冲区

ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

while (socketChannel.read(byteBuffer) != -1) {

byteBuffer.flip();

fileChannel.write(byteBuffer);

byteBuffer.clear();

}

socketChannel.close();

fileChannel.close();

serverSocketChannel.close();

}

}

非阻塞式网络通信


package NIOAndBIO;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.util.Iterator;

import java.util.Scanner;

public class NIO {

public static void main(String[] args) {

Thread thread1 = new Thread(()->{

try {

server();

} catch (IOException e) {

e.printStackTrace();

}

});

Thread thread2 = new Thread(()->{

try {

client();

} catch (IOException e) {

e.printStackTrace();

}

});

thread1.start();

thread2.start();

}

public static void client() throws IOException {

SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(“127.0.0.1”, 2020));

// 设置为非阻塞模式

socketChannel.configureBlocking(false);

ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

Scanner scanner = new Scanner(System.in);

while (scanner.hasNext()) {

String str = scanner.next();

byteBuffer.put(str.getBytes());

byteBuffer.flip();

socketChannel.write(byteBuffer);

byteBuffer.clear();

}

byteBuffer.clear();

socketChannel.close();

}

public static void server() throws IOException {

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.configureBlocking(false);

serverSocketChannel.bind(new InetSocketAddress(2020));

// 获得选择器

Selector selector = Selector.open();

// 将通道注册到选择器中,设定为接收操作

最后

码字不易,觉得有帮助的可以帮忙点个赞,让更多有需要的人看到

又是一年求职季,在这里,我为各位准备了一套Java程序员精选高频面试笔试真题,来帮助大家攻下BAT的offer,题目范围从初级的Java基础到高级的分布式架构等等一系列的面试题和答案,用于给大家作为参考

以下是部分内容截图
架构面试专题及架构学习笔记导图.png

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
img

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
er.allocate(1024);

Scanner scanner = new Scanner(System.in);

while (scanner.hasNext()) {

String str = scanner.next();

byteBuffer.put(str.getBytes());

byteBuffer.flip();

socketChannel.write(byteBuffer);

byteBuffer.clear();

}

byteBuffer.clear();

socketChannel.close();

}

public static void server() throws IOException {

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.configureBlocking(false);

serverSocketChannel.bind(new InetSocketAddress(2020));

// 获得选择器

Selector selector = Selector.open();

// 将通道注册到选择器中,设定为接收操作

最后

码字不易,觉得有帮助的可以帮忙点个赞,让更多有需要的人看到

又是一年求职季,在这里,我为各位准备了一套Java程序员精选高频面试笔试真题,来帮助大家攻下BAT的offer,题目范围从初级的Java基础到高级的分布式架构等等一系列的面试题和答案,用于给大家作为参考

以下是部分内容截图
[外链图片转存中…(img-E6ow04uE-1713455846149)]

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
[外链图片转存中…(img-hAJgnRPw-1713455846150)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 24
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值