• Java NIO


    示例代码:https://github.com/kuotian/TestSpring/tree/master/03nioTest

    一、简介

    Java NIO(New IO)是从Java 1.4版本开始引入的一个新的IO API,可以替代标准的Java IO API。NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的、基于通道的IO操作。NIO将以更加高效的方式进行文件的读写操作。

    Java NIO 与IO 的主要区别

    IO NIO
    面向流(Stream Oriented) 面向缓冲区(Buffer Oriented)
    阻塞IO(Blocking IO) 非阻塞IO(NonBlocking IO)
    (无) 选择器(Selectors)

    Java NIO系统的核心在于:通道(Channel)和缓冲区(Buffer)。通道表示打开到IO 设备(例如:文件、套接字)的连接。若需要使用NIO 系统,需要获取用于连接IO 设备的通道以及用于容纳数据的缓冲区。然后操作缓冲区,对数据进行处理。
    简而言之,Channel 负责传输,Buffer 负责存储

    二、缓冲区 Buffer

    一个用于特定基本数据类型的容器。由java.nio 包定义的,所有缓冲区都是Buffer 抽象类的子类。Java NIO中的Buffer 主要用于与NIO 通道进行交互,数据是从通道读入缓冲区,从缓冲区写入通道中的。

    Buffer 就像一个数组,可以保存多个相同类型的数据。根据数据类型不同(boolean 除外) ,有以下Buffer 常用子类:ByteBuffer、CharBuffer、ShortBuffer、IntBuffer、LongBuffer、FloatBuffer、DoubleBuffer。

    Buffer 中的重要概念

    • 容量(capacity) :表示Buffer 最大数据容量,缓冲区容量不能为负,并且创建后不能更改。
    • 限制(limit):第一个不应该读取或写入的数据的索引,即位于limit 后的数据不可读写。缓冲区的限制不能为负,并且不能大于其容量。
    • 位置(position):下一个要读取或写入的数据的索引。缓冲区的位置不能为负,并且不能大于其限制
    • 标记(mark)与重置(reset):标记是一个索引,通过Buffer 中的mark() 方法指定Buffer 中一个特定的position,之后可以通过调用reset() 方法恢复到这个position

    标记、位置、限制、容量遵守以下不变式:0<= mark <= position <= limit <= capacity

    缓冲区的数据操作

    创建一个容量为capacity 的 Buffer 对象:static XxxBuffer allocate(int capacity)

    获取Buffer 中的数据

    • get() :读取单个字节
    • get(byte[] dst):批量读取多个字节到dst 中
    • get(int index):读取指定索引位置的字节(不会移动position)

    放入数据到Buffer 中

    • put(byte b):将给定单个字节写入缓冲区的当前位置
    • put(byte[] src):将src 中的字节写入缓冲区的当前位置
    • put(int index, byte b):将指定字节写入缓冲区的索引位置(不会移动position)

    Buffer 中的常用方法

    方法 描述
    Buffer clear() 清空缓冲区并返回对缓冲区的引用
    Buffer flip() 将缓冲区的界限设置为当前位置,并将当前位置充值为0
    int capacity() 返回Buffer 的capacity大小
    boolean hasRemaining() 判断缓冲区中是否还有元素
    int limit() 返回Buffer 的界限(limit) 的位置
    Buffer limit(int n) 将设置缓冲区界限为n, 并返回一个具有新limit 的缓冲区对象
    Buffer mark() 对缓冲区设置标记
    int position() 返回缓冲区的当前位置position
    Buffer position(int n) 将设置缓冲区的当前位置为n , 并返回修改后的Buffer 对象
    int remaining() 返回position 和limit 之间的元素个数
    Buffer reset() 将位置position 转到以前设置的mark 所在的位置
    Buffer rewind() 将位置设为为0,取消设置的mark
    代码示例:
    public static void test1(){
        //1.分配一个指定大小的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        printInfo("allocate", buffer);  // position:0  limit:1024  capacity:1024
        //2.利用put()存入数据到缓冲区
        buffer.put(str.getBytes());
        printInfo("put", buffer);   // position:5  limit:1024  capacity:1024
        //3.切换读取数据的模式
        buffer.flip();
        printInfo("flip", buffer); // position:0  limit:5  capacity:1024
        //4.利用get()读取缓冲区的数据
        byte[] dst = new byte[buffer.limit()];
        buffer.get(dst);
        System.out.println(new String(dst)); // abcde
        printInfo("get", buffer);   // position:5  limit:5  capacity:1024
        //5.rewind()
        buffer.rewind();
        printInfo("rewind", buffer);    // position:0  limit:5  capacity:1024
        //6.clear():清空缓冲区 只是恢复position、limit的值,并不真的清空其中数据,下次操作后覆盖
        buffer.clear();
        printInfo("clear", buffer);     // position:0  limit:1024  capacity:1024
    }
    
    public static void test2(){
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(str.getBytes());
        buffer.flip();
        byte[] dst = new byte[buffer.limit()];
        buffer.get(dst, 0 ,2);
        System.out.println(new String(dst, 0 ,2)); //ab
    
        System.out.println(buffer.position()); // 2
    
        //mark():标记
        buffer.mark();
        buffer.get(dst, 2, 2);
        System.out.println(buffer.position()); // 4
    
        //reset():恢复到mark的位置
        buffer.reset();
        System.out.println(buffer.position()); // 2
    
        //判断缓冲区中是否还有剩余数据
        if(buffer.hasRemaining()){
            // 获取缓冲区中可以操作的数量
            System.out.println(buffer.remaining()); // 3
        }
    }
    

    非直接 与 直接 缓冲区

    字节缓冲区ByteBuffer,可以使非直接的,也可以是直接的。其他子类Buffer只能创建非直接的缓冲区。

    字节缓冲区是直接缓冲区还是非直接缓冲区可通过调用其isDirect()方法来确定。提供此方法是为了能够在性能关键型代码中执行显式缓冲区管理。

    非直接缓冲区

    通过allocate()方法分配缓冲区,将缓冲区建立在JVM的内存中。

    直接缓冲区

    通过allocateDirect()方法分配直接缓冲区,将缓冲区建立在物理内存中。

    直接字节缓冲区,则Java 虚拟机会尽最大努力直接在此缓冲区上执行本机I/O 操作。也就是说,在每次调用基础操作系统的一个本机I/O 操作之前(或之后),虚拟机都会尽量避免将缓冲区的内容复制到中间缓冲区中(或从中间缓冲区中复制内容)。

    直接字节缓冲区可以通过调用此类的allocateDirect() 工厂方法来创建。此方法返回的缓冲区进行分配和取消分配所需成本通常高于非直接缓冲区。直接缓冲区的内容可以驻留在常规的垃圾回收堆之外,因此,它们对应用程序的内存需求量造成的影响可能并不明显。所以,建议将直接缓冲区主要分配给那些易受基础系统的本机I/O 操作影响的大型、持久的缓冲区。一般情况下,最好仅在直接缓冲区能在程序性能方面带来明显好处时分配它们。

    直接字节缓冲区还可以通过FileChannel 的map() 方法将文件区域直接映射到内存中来创建。该方法返回MappedByteBuffer。Java 平台的实现有助于通过JNI 从本机代码创建直接字节缓冲区。如果以上这些缓冲区中的某个缓冲区实例指的是不可访问的内存区域,则试图访问该区域不会更改该缓冲区的内容,并且将会在访问期间或稍后的某个时间导致抛出不确定的异常。

    代码示例:
    public static void test3(){
        // 分配直接缓冲区
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        System.out.println(buffer.isDirect()); // true
    }
    

    三、通道Channel

    由java.nio.channels 包定义的。Channel 用于 源节点 与 目标节点的连接。Channel 类似于传统的“流”。只不过Channel 本身不能直接存储数据,因此需要配合缓冲区进行传输。

    应用程序调用底层的IO接口的读写方法,进行对磁盘中数据的读写操作。早期,IO接口都是由CPU独立负责,当应用层程序发起大量读写请求时,CPU占用率非常高,CPU利用率低,性能下降。之后,引入DMA,CPU 初始化这个传输动作,传输动作本身是由 DMA 控制器来实行和完成。但是,在实现DMA传输时,是由DMA控制器直接掌管总线。DMA传输前,CPU要把总线控制权交给DMA控制器,而在结束DMA传输后,DMA控制器应立即把总线控制权再交回给CPU。当应用层程序发起大量读写请求时,在数据的传送期间,CPU长时间无法控制总线。

    通道是完全独立的处理器,有自己的指令和程序,具有更强的独立处理数据输入和输出的能力。

    通道解决了两个问题:

    1. 由CPU承担输入输出的工作。虽然DMA无需CPU进行外设与内存的数据交换工作,但是这只是减少了CPU的负担。因而DMA中,输入输出的初始化仍然要由CPU来完成。
    2. 大型计算机系统中高速设备共享DMA接口的问题。大型计算机系统的外设太多以至于不得不共享有限的DMA接口(小型计算机系统比如pc机中每个高速设备分配一个DMA接口)。

    Channel 的主要实现类

    java.nio.channels.Channel接口:

    • FileChannel:用于读取、写入、映射和操作文件的通道。
    • DatagramChannel:通过UDP 读写网络中的数据通道。是一个能收发UDP包的通道。
    • SocketChannel:通过TCP 读写网络中的数据。是一个连接到TCP网络套接字的通道。
    • ServerSocketChannel:可以监听新进来的TCP 连接,就像标准IO中的ServerSocket一样。对每一个新进来的连接都会创建一个SocketChannel。

    获取通道

    1. Java针对支持通道的类提供了getChannell() 方法

      本地IO
      FileInputStream / FileOutputStream
      VRandomAccessFile

      网络IO
      Socket
      ServerSocket
      DatagramSocket

    2. JDK1.7 通过通道的静态方法open() 打开并返回指定通道。

    3. 使用Files 类的静态方法newByteChannel() 获取字节通道。

    代码示例
    //1. 利用通道完成文件的复制(非直接缓冲区)
    public static void test1(){
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            fileInputStream = new FileInputStream("1.jpg");
            fileOutputStream = new FileOutputStream("2.jpg");
            //① 获取通道
            inChannel = fileInputStream.getChannel();
            outChannel = fileOutputStream.getChannel();
            //② 分配指定大小的缓冲区
            ByteBuffer buf = ByteBuffer.allocate(1024);
            //③ 将通道中的数据存入缓冲区中
            while (inChannel.read(buf) != -1){
                buf.flip(); // 切换成读取数据的模式
                //④将缓冲区的数据写入通道中
                outChannel.write(buf);
                buf.clear(); // 清空缓冲区
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeChannel(outChannel);
            closeChannel(inChannel);
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    //2. 利用直接缓冲区完成文件的复制(内存映射文件)
    public static void test2() {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
            outChannel = FileChannel.open(Paths.get("3.jpg"), StandardOpenOption.WRITE,StandardOpenOption.READ, StandardOpenOption.CREATE_NEW);
    
            //内存映射文件
            MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
            MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE,0, inChannel.size());
            //直接对缓冲区进行数据的读写操作
            byte[] dst = new byte[inMappedBuf.limit()];
            inMappedBuf.get(dst);
            outMappedBuf.put(dst);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeChannel(inChannel);
            closeChannel(outChannel);
        }
    }
    

    通道之间的数据传递

    • public abstract long transferFrom(ReadableByteChannel src, long position, long count):将数据从源通道传输到其他Channel 中

    • public abstract long transferFrom(ReadableByteChannel src, long position, long count):将数据从源通道传输到其他Channel 中

    代码示例:
    //通道之间的数据传递(直接缓冲区)
    public static void test3() {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
            outChannel = FileChannel.open(Paths.get("4.jpg"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE_NEW);
    
    //        inChannel.transferTo(0, inChannel.size(), outChannel);
            outChannel.transferFrom(inChannel, 0, inChannel.size());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeChannel(inChannel);
            closeChannel(outChannel);
        }
    }
    

    分散(Scatter)和聚集(Gather)

    • 分散读取(Scattering Reads):从Channel 中读取的数据“分散”到多个Buffer 中。
      注意:按照缓冲区的顺序,从Channel 中读取的数据依次将Buffer 填满。

    • 聚集写入(Gathering Writes):将多个Buffer 中的数据“聚集”到Channel中。
      注意:按照缓冲区的顺序,写入position 和limit 之间的数据到Channel 。

    示例代码
    // 分散于聚集
    public static void test4() throws IOException {
        RandomAccessFile raf1 = new RandomAccessFile("1.txt", "rw");
        //1.获取通道
        FileChannel channel1 = raf1.getChannel();
        //2.分配指定大小的缓冲区
        ByteBuffer buf1 = ByteBuffer.allocate(100);
        ByteBuffer buf2 = ByteBuffer.allocate(1024);
        //3.分散读取
        ByteBuffer[] bufs = {buf1, buf2};
        channel1.read(bufs);
        for (ByteBuffer byteBuffer : bufs){
            byteBuffer.flip();
        }
        System.out.println(new String(bufs[0].array(), 0, bufs[0].limit()));
        System.out.println("---------------------");
        System.out.println(new String(bufs[1].array(), 0, bufs[1].limit()));
    
        //4.聚集写入
        RandomAccessFile raf2 = new RandomAccessFile("2.txt", "rw");
        FileChannel channel2 = raf2.getChannel();
        channel2.write(bufs);
    }
    

    FileChannel 的常用方法

    方法 描述
    int read(ByteBuffer dst) 从Channel 中读取数据到ByteBuffer
    long read(ByteBuffer[] dsts) 将Channel 中的数据“分散”到ByteBuffer[]
    int write(ByteBuffer src) 将ByteBuffer 中的数据写入到Channel
    long write(ByteBuffer[] srcs) 将ByteBuffer[] 中的数据“聚集”到Channel
    long position() 返回此通道的文件位置
    FileChannel position(long p) 设置此通道的文件位置
    long size() 返回此通道的文件的当前大小
    FileChannel truncate(long s) 将此通道的文件截取为给定大小
    void force(boolean metaData) 强制将所有对此通道的文件更新写入到存储设备中

    四、Selector

    选择器(Selector)是SelectableChannle 对象的多路复用器,Selector 可以同时监控多个SelectableChannel 的IO 状况,也就是说,利用Selector 可使一个单独的线程管理多个Channel,从而管理多个网络连接。Selector 是非阻塞IO 的核心。

    SelectableChannle 的结构:

    为什么使用Selector?

    Selector(选择器)是Java NIO中能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写事件做好准备的组件。这样,一个单独的线程可以管理多个channel,从而管理多个网络连接。

    仅用单个线程来处理多个Channels的好处是,只需要更少的线程来处理通道。事实上,可以只用一个线程处理所有的通道。对于操作系统来说,线程之间上下文切换的开销很大,而且每个线程都要占用系统的一些资源(如内存)。因此,使用的线程越少越好。

    但是,需要记住,现代的操作系统和CPU在多任务方面表现的越来越好,所以多线程的开销随着时间的推移,变得越来越小了。实际上,如果一个CPU有多个内核,不使用多任务可能是在浪费CPU能力。不管怎么说,关于那种设计的讨论应该放在另一篇不同的文章中。在这里,只要知道使用Selector能够处理多个通道就足够了。

    选择器(Selector)的应用

    Selector的创建

    通过调用Selector.open()方法创建一个Selector:Selector selector = Selector.open();

    向Selector注册通道

    为了将Channel和Selector配合使用,必须将channel注册到selector上。通过SelectableChannel.register()方法来实现:

    SelectableChannel.register(Selector sel, int ops)

    //创建一个Socket套接字
    Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9898);
    //获取SocketChannel
    SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
    //创建选择器
    Selector selector = Selector.open();
    //将SocketChannel切换到非阻塞模式
    socketChannel.configureBlocking(false);
    //向Selector注册Channel
    SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);
    

    与Selector一起使用时,Channel必须处于非阻塞模式下。这意味着不能将FileChannel与Selector一起使用,因为FileChannel不能切换到非阻塞模式。而套接字通道都可以。

    register()方法的第二个参数。这是一个“interest集合”,意思是在通过Selector监听Channel时对什么事件感兴趣。

    可以监听的事件类型(可使用SelectionKey 的四个常量表示):

    • 读: SelectionKey.OP_READ (1)
    • 写: SelectionKey.OP_WRITE (4)
    • 连接: SelectionKey.OP_CONNECT(8)
    • 接收: SelectionKey.OP_ACCEPT (16)

    若注册时不止监听一个事件,则可以使用“位或”操作符连接。

    //注册“监听事件”
    int interestSet = SelectonKey.OP_READ | SelectonKey.OP_WRITE;
    

    SelectionKey

    表示SelectableChannel 和Selector 之间的注册关系。每次向选择器注册通道时就会选择一个事件(选择键)。选择键包含两个表示为整数值的操作集。操作集的每一位都表示该键的通道所支持的一类可选择操作。

    方法 描述
    int interestOps() 获取感兴趣事件集合
    int readyOps() 获取通道已经准备就绪的操作的集合
    SelectableChannel channel() 获取注册通道
    Selector selector() 返回选择器
    boolean isReadable() 检测Channal 中读事件是否就绪
    boolean isWritable() 检测Channal 中写事件是否就绪
    booleanisConnectable() 检测Channel 中连接是否就绪
    booleanisAcceptable() 检测Channel 中接收是否就绪

    NIO 的非阻塞式网络通信

    Client
    public class NonBlockingNIO_Client {
        public static void main(String[] args) throws IOException {
            client();
        }
    
        public static void client() throws IOException {
            //1.获取通道
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
            //2.切换成非阻塞模式
            socketChannel.configureBlocking(false);
            //3.分配指定大小的缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //4.发送数据给服务端
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()){
                String str = scanner.next();
                byteBuffer.put((new Date().toString()+"
    "+str).getBytes());
                byteBuffer.flip();
                socketChannel.write(byteBuffer);
                byteBuffer.clear();
            }
            //5.关闭通道
            socketChannel.close();
        }
    }
    
    Server
    public class NonBlockingNIO_Server {
        public static void main(String[] args) throws IOException {
            server();
        }
    
        public static void server() throws IOException {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //2.切换成非阻塞模式
            serverSocketChannel.configureBlocking(false);
            //3.绑定连接
            serverSocketChannel.bind(new InetSocketAddress(9898));
            //4.获取选择器
            Selector selector = Selector.open();
            //5.将通道注册到选择器,并且制定“监听接收事件”
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    
            //6.轮询式的获取选择器上已经“准备就绪”事件
            while (selector.select() > 0){
                //7.获取当前选择器其中所有注册的“选择键”(已就绪的监听事件)
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while(it.hasNext()){
                    //8.获取准备就绪的是事件
                    SelectionKey sk = it.next();
                    //9.判断具体是什么事件准备就绪
                    if(sk.isAcceptable()){
                        //10.若“接收就绪”,获取客户端连接
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        //11.切换非阻塞模式
                        socketChannel.configureBlocking(false);
                        //12.非该通道注册到选择器上
                        socketChannel.register(selector, SelectionKey.OP_READ);
    
                    }else if(sk.isReadable()){
                        //13.获取当前选择器上“读就绪”状态的通道
                        SocketChannel socketChannel = (SocketChannel)sk.channel();
                        //14.读取数据
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        int len = 0;
                        while((len = socketChannel.read(byteBuffer)) > 0){
                            byteBuffer.flip();
                            System.out.println(new String(byteBuffer.array(), 0, len));
                            byteBuffer.clear();
                        }
                    }
                    //15.取消选择键SelectionKey
                    it.remove();
                }
            }
        }
    }
    

    五、管道Pipe

    Java NIO 管道是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。

    创建管道

    通过Pipe.open()方法打开管道。例如:Pipe pipe = Pipe.open();

    向管道写数据

    要向管道写数据,需要访问sink通道。Pipe.SinkChannel sinkChannel = pipe.sink();

    通过调用SinkChannel的write()方法,将数据写入SinkChannel:sinkChannel.write(byteBuffer);

    从管道读取数据

    从读取管道的数据,需要访问source通道:Pipe.SourceChannel sourceChannel = pipe.source();

    调用source通道的read()方法来读取数据:

    ByteBuffer buf = ByteBuffer.allocate(48);
    int bytesRead = sourceChannel.read(buf);
    

    read()方法返回的int值会告诉我们多少字节被读进了缓冲区。

    代码示例
    public void testPipe() throws IOException {
        //1.获取管道
        Pipe pipe = Pipe.open();
        //2.将缓冲区中的数据写入管道
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Pipe.SinkChannel sinkChannel = pipe.sink();
        byteBuffer.put("通过单向管道发送数据".getBytes());
        byteBuffer.flip();
        sinkChannel.write(byteBuffer);
    
        //3.读取缓冲区中的数据
        Pipe.SourceChannel sourceChannel = pipe.source();
        byteBuffer.flip();
        int len = sourceChannel.read(byteBuffer);
        System.out.println(new String(byteBuffer.array(), 0, len));
    
        sourceChannel.close();
        sinkChannel.close();
    }
    

    参考资料

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

    https://ifeve.com/overview/

  • 相关阅读:
    外设驱动库开发笔记5:AD7705系列ADC驱动
    ROS+LEDE最强上网软路由
    Flume1.9.0的安装、部署、简单应用(含分布式、与Hadoop3.1.2、Hbase1.4.9的案例)
    通过 Sqoop1.4.7 将 Mysql5.7、Hive2.3.4、Hbase1.4.9 之间的数据导入导出
    Hadoop 3.1.2(HA)+Zookeeper3.4.13+Hbase1.4.9(HA)+Hive2.3.4+Spark2.4.0(HA)高可用集群搭建
    Centos7 二进制安装 Kubernetes 1.13
    Centos7 使用 kubeadm 安装Kubernetes 1.13.3
    go get获取gitlab私有仓库的代码
    Nginx设置Https反向代理,指向Docker Gitlab11.3.9 Https服务
    Docker 创建 Bamboo6.7.1 以及与 Crowd3.3.2 实现 SSO 单点登录
  • 原文地址:https://www.cnblogs.com/kuotian/p/13208184.html
Copyright © 2020-2023  润新知