java nio 学习笔记

Java NIO(New IO)是一个可以替代标准 Java IO 的 API(从Java 1.4开始),提供了与标准IO 不同的工作方式。

Java NIO: Channels and Buffers(通道和缓冲区)

标准的 IO 基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(Buffer)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。

Java NIO: Non-blocking IO(非阻塞IO)

Java NIO 可以让你非阻塞的使用 IO,例如:当线程从通道(Channel)读取数据到缓冲区时(Buffer),线程还是可以进行其他事情。当数据被写入到缓冲区时,线程可以继续处理它。从缓冲区写入通道也类似。

Java NIO: Selectors(选择器)

Java NIO引入了选择器(Selector)的概念,选择器用于监听多个通道(Channel)的事件(比如:连接打开,数据到达)。因此,单个的线程可以监听多个数据通道(Channel)。

selector

Linux epoll 的水平触发模式

  1. 对于读操作 只要缓冲内容不为空,LT模式返回读就绪。
  2. 对于写操作 只要缓冲区还不满,LT模式会返回写就绪。

所以,Linux epoll的水平触发是以缓冲区空满状态来判断的

测试

import java.net.InetSocketAddress;
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.concurrent.TimeUnit;

/**
 * NIO 水平触发测试
 * 验证java nio水平触发的办法是客户端写多个字节(比如1000个),服务端每次都不读取字节,缓冲区一直没读完,处于非空状态。由于水平触发,读事件应当会一直触发。
 *
 * @author N3verL4nd
 * @date 2021/7/20
 */
public class NioLevelTriggerServer {
    public static void main(String[] argv) throws Exception {
        Selector selector = Selector.open();
        ServerSocketChannel server = ServerSocketChannel.open();
        server.bind(new InetSocketAddress("0.0.0.0", 8888));
        server.configureBlocking(false);
        server.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            int n = selector.select();
            if (n == 0) {
                continue;
            }

            System.out.println("Select " + n);

            Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
            while (keys.hasNext()) {
                SelectionKey key = keys.next();
                keys.remove();
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel accept = channel.accept();
                    accept.configureBlocking(false);
                    accept.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();

                    // 不读取任何数据,缓冲区始终不为空
                }
            }
            System.out.println("休眠一秒, 减缓输出, 便于观察");
            TimeUnit.SECONDS.sleep(1);
        }
    }
}

image-20210720130641377

或者使用如下脚本

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author N3verL4nd
 * @date 2021/7/20
 */
public class NioLevelTriggerClient {
    public static void main(String[] args) throws IOException {

        SocketChannel socketChannel = SocketChannel.open();

        InetAddress ia = InetAddress.getLocalHost();
        InetSocketAddress isa = new InetSocketAddress(ia, 8888);
        socketChannel.connect(isa);
        socketChannel.configureBlocking(false);
        System.out.println("与服务器的连接建立成功!");
        socketChannel.write(StandardCharsets.UTF_8.encode("hello world"));

        socketChannel.close();
    }
}

所以,Java nio 是水平触发。

linux epoll 默认也是水平触发。

#include <unistd.h>
#include <stdio.h>
#include <sys/epoll.h>

int main()
{
    int epfd, nfds;
    char buf[1];
    struct epoll_event event, events[5];
    epfd = epoll_create(1);
    event.data.fd = STDIN_FILENO;
    event.events = EPOLLIN;  // LT是默认模式
    epoll_ctl(epfd, EPOLL_CTL_ADD, STDIN_FILENO, &event);
    while (1) {
        nfds = epoll_wait(epfd, events, 5, -1);
        int i;
        for (i = 0; i < nfds; ++i) {
            if (events[i].data.fd == STDIN_FILENO) {
                printf("hello world\n");
            }
        }
    }
}

会一直输出 hello world。

http://tutorials.jenkov.com/java-nio/index.html

http://ifeve.com/java-nio-all/
https://tech.meituan.com/2016/11/04/nio.html
https://www.zhihu.com/question/29005375
https://zhuanlan.zhihu.com/p/25701512
https://zhuanlan.zhihu.com/p/25914350
https://zhuanlan.zhihu.com/p/26243285

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

N3verL4nd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值