Java中的NIO

NIO的使用

0. 从传统Socket开始

首先写一个简单的echo服务器:

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoService {
    public void start(){
        try {
            ServerSocket server = new ServerSocket();
            server.bind(new InetSocketAddress("localhost",7788));
            while (true) {
                Socket socket = server.accept();
                new Thread(new EchoRunnable(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public class EchoRunnable implements Runnable{
        private Socket socket;

        public EchoRunnable(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            System.out.println("链接成功");
            BufferedReader br = null;
            PrintWriter pw = null;
            try {
                InputStream is = socket.getInputStream();
                br = new BufferedReader(new InputStreamReader(is));

                OutputStream os = socket.getOutputStream();
                pw = new PrintWriter(new OutputStreamWriter(os));

                String line;

                while ((line = br.readLine()) != null){
                    System.out.println("接收:"+line);

                    pw.println("Echo:" + line);
                    pw.flush();
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (pw != null) {
                    pw.close();
                }
                if (socket != null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        EchoService echoService = new EchoService();
        echoService.start();
    }
}

这是一个简单的tcp-Echo服务器,其整体的思路是服务器通过accept()方法来等待客户端的链接,如果有客户端链接上了,则开启一个新的线程来与客户端进行通信,否则则一直在这个方法上等待.
之所以使用多线程,主要原因在socket.accept(),和读流,写流着三个主要函数是都是同步阻塞的,当一个连接在处理IO的时候,系统是阻塞的,如果是单线程的话,整个系统必然就挂死在这里,但是启用多线程,就可以让CPU去处理更多的事情,这也是使用多线程的本质

  • 利用多核
  • 当I/O阻塞系统,单CPU空闲的时候,可以利用多线程使用CPU资源

这种模型在活动链接数不是特别高的情况下还是比较不错的,可以让每一个连接专注于自己的IO并且编程模型简单,也不用过多考虑过载,限流等问题,但是这个模型最本质的问题在于,严重依赖于线程,但线程是很贵的资源,主要表现在:

  1. 线程的创建和销毁成本很高,在Linux这样的操作系统中,线程本质上就是一个进程,创建和销毁都是重量级的系统函数
  2. 线程本身占用较大的内从,像Java的线程栈,一般至少要分配512k-1M的空间,如果系统中的线程数过千,恐怕整个JVM的内存都会被吃掉一半。
  3. 线程的切换成本是很高的。操作系统发生线程切换的时候,需要保留线程的上下文,然后执行系统调用。如果线程数过高,可能执行线程切换的时间甚至会大于线程执行的时间,这时候带来的表现往往是系统load偏高、CPU sy(内核空间占用CPU百分比)使用率特别高(超过20%以上),导致系统几乎陷入不可用的状态
  4. 容易造成锯齿状的系统负载。因为系统负载是用活动线程数或CPU核心数,一旦线程数量高但外部网络环境不是很稳定,就很容易造成大量请求的结果同时返回,激活大量阻塞线程从而使系统负载压力过大。

1. NIO概述

NIO(Non-blocking I/O),是一种同步非阻塞的I/O模型,也是I/O多路复用的基础,已经被越来越多地应用到大型应用服务器,成为解决高并发与大量连接、I/O处理问题的有效方式
NIO有三个核心类:Channel,Buffer,Selector

Channel

Channel国内翻译成”通道”,Chanel和IO中的Stream差不多是一个等级的,只不过Stream是单向的,而Channel是双向的,既可以用来进行读操作,也可以用来进行写操作,NIO中的Channel的主要实现有:

  • FileChannel: 文件IO
  • DatagramChannel: UDP
  • SocketChannel: TCP-Client
  • ServerSocketChannel: TCP-Server

Selector

Selector运行单线程处理多个Channel,如果应用打开了多个通道,但每个连接的流量都很低,使用Selector就会非常方便

2. FileChannel

首先从FileChannel来看NIO的使用,使用BIO在进行读文件时代码如下:

public static void withBIO() {
    InputStream in = null;
    try {
        in = new FileInputStream("src/aa.txt");
        byte[] buf = new byte[1024];
        int bytesRead = in.read(buf);
        while (bytesRead != -1){
            for (int i = 0; i < bytesRead; i++) {
                System.out.print((char)buf[i]);
            }
            bytesRead = in.read(buf);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

输出结果:

在看使用NIO的代码:

public static void withNio(){
    FileInputStream aFile = null;
    try {
        aFile = new FileInputStream("src/aa.txt");
        FileChannel fileChannel = aFile.getChannel();
        ByteBuffer buf = ByteBuffer.allocate(1024);
        //读
        while (fileChannel.read(buf) != -1){
            buf.flip();
            while (buf.hasRemaining()){
                System.out.print((char)buf.get());
            }
            buf.compact();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (aFile != null) {
            try {
                aFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

输出结果:

与使用传统的BIO是一样的,仔细观察这两段代码,在获取输入流之前,是一样的操作,不同的地方在于从FileInputStream中读取数据的操作,并且可以看到在BIO中是将数据读到一个byte数组中,而在NIO中是将数据读到ByteBuffer中

Buffer

根据之前的介绍,ByteBuffer是Buffer的子类,可以把Buffer理解为一组基本数据类型的元素列表,根据读取文件的代码可以看出使用Buffer一般遵循下面几个步骤:
1. 分配空间: ByteBuffer buf = ByteBuffer.allocate(1024);
2. 将数据*放入*Buffer中: fileChannel.read(buf)
3. 调用 filp()方法: buf.flip();, 这一步是使用Buffer与byte[]的重要区别,之后会详细说明
4. 将Buffer中的数据取出: ((char)buf.get()
5. 调用compact()方法

Buffer, 顾名思义: 缓冲区,实际上是一个容器,一个连续数组.Channel提供从文件,网络读取数据的渠道,但是读写的数据必须都经过Buffer,可以吧Buffer简单的理解为一组基本数据类型的元素列表,它通过几个变量来保存这个数据的当前位置状态: capacity,position,limit,mark,如下表:

变量说明
capacity缓冲区数组的总长度
position下一个要操作的数据元素的位置
limit缓冲区数组中不可操作的下一个元素的位置(limit<=capacity)
mark用于记录当前position的前一个位置或默认是0


例如: 我们通过ByteBuffer.allocate(11)方法创建了一个11个byte的数组的缓冲区,初始状态如上图,position的位置为0,
capacity和limit默认都是数组长度。当我们从文件读取5个字节时,变化如下图:

此时可以认为已经从文件中读取到了5个字节进入到了Buffer中,此时我们需要将缓冲区中的5个字节数据读取出来,所以我们调用ByteBuffer.flip()方法,变化如下图所示(position设回0,并将limit设成之前的position的值):

这时我们通过buf.get()方法就能从BUffer中获取这5个字节的数据,并显示出来了,在下一次读取数据之前,我们再调用clear()compact()方法,缓冲区的索引又会回到了初始位置,即图一所示;

clear和compact

当调用clear或compact方法时,position都将被设回0,limit设置为capacity,换句话说,Buffer被清空了,其实Buffer中的数据并未被真的清空,只是这些表姐告诉我们从哪里开始往Buffer里写数据,如果Buffer中有一些未读的数据,调用clear()方法,数据将“被遗忘”,意味着不再有任何标记会告诉你哪些数据被读过,哪些还没有。如果Buffer中仍有未读的数据,且后续还需要这些数据,但是此时想要先先写些数据,那么使用compact()方法。compact()方法将所有未读的数据拷贝到Buffer起始处。然后将position设到最后一个未读元素正后面。limit属性依然像clear()方法一样,设置成capacity。现在Buffer准备好写数据了,但是不会覆盖未读的数据。

修改代码:

public static void withNio(){
    FileInputStream aFile = null;
    try {
        aFile = new FileInputStream("src/aa.txt");
        FileChannel fileChannel = aFile.getChannel();
        // Buffer长度为3个字节
        ByteBuffer buf = ByteBuffer.allocate(3);
        //读
        while (fileChannel.read(buf) != -1){
            buf.flip();
            while (buf.hasRemaining()){
                System.out.println((char)buf.get());
                // 读取到2个字节则跳出循环
                if (buf.position() == 2){
                    break;
                }
            }
            //clear丢弃掉未读的数据
            buf.clear();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (aFile != null) {
            try {
                aFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

首先将文件内容修改为abcde,并且Buffer的总长度修改为3个字节,当读取完2个字节时就跳出循环,此时Buffer中应当还有一个字节未读取,首先看clear方法:

此时已经读取了2个字节,控制台输出了ab,第三个字节在Buffer中,应当为字母c,当调用clear之后:

发现字母c虽然没有读取,但是已经被丢弃了,buffer中再次读取的数据长度为2个字节(一共5字节);
再看compact:

当读取完两个字节之后,效果与clear相同,

但是当执行完compact之后,pos并没有归0,而是变成了1,因为之前在Buffer中有一个字节的数据并没有被读取出来,继续执行

可以看出,字母c并没有被丢弃,而是正确的读取出来了,并且lim长度也是3(一共为5,第一次读了2字节,还剩3字节)

Buffer写入

与BIO不同,Buffer可以同时支持读取和写入,读取是Channel将数据放入Buffer,再从Buffer中将数据读出来;而写入是将数据写入Buffer再有Buffer写入到Channel,而具体数据写入到文件还是网络中是有Channel来决定的,要想写入数据,那么Channel则必须拥有写的能力,我们之前的代码中Channel是从输入流中获得的(FileChannel fileChannel = aFile.getChannel();),所以不具备写的能力

public static void readAndWrite(){
    FileChannel channel = null;
    try {
        RandomAccessFile file = new RandomAccessFile("src/nio.txt","rw");
        channel = file.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(3);
        //写
        buffer.put("abc".getBytes());
        buffer.flip();
        channel.write(buffer);
        file.seek(0);//重置文件指针,RandomAccessFile的方法
        //读
        buffer.clear();
        while (channel.read(buffer) != -1){
            buffer.flip();
            while (buffer.hasRemaining()){
                System.out.print((char) buffer.get());
            }
            buffer.compact();
        }
    }  catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (channel != null){
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

使用RandomAccessFile来进行测试,RandomAccessFile同时具备写和读的能力,所以从中获得的Channel可以同时写和读

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

通过调用Buffer.mark()方法,可以标记Buffer中的一个特定的position,之后可以通过调用Buffer.reset()方法恢复到这个position。Buffer.rewind()方法将position设回0,所以你可以重读Buffer中的所有数据。limit保持不变,仍然表示能从Buffer中读取多少个元素。

3. SocketChannel

SocketChannel对应着TCP链接中的客户端,服务器还是使用Echo服务器,使用NIO来完成代码,示例如下:

“`java
private void start() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketChannel socketChannel = null;
try {
socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress(“localhost”, 7788));
for (int i = 0; i < 3; i++) {
String info = “这是第” + i + “条信息\n”;
buffer.clear();
buffer.put(info.getBytes());
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
socketChannel.read(buffer);
buffer.flip();
System.out.println(new String(buffer.array(), 0, buffer.limit()));

    }
    socketChannel.close();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (socketChannel != null) {
        try {
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}
“`

运行结果如下:
Service

Client

可以看到是正常运行的,与之前的BIO形式的Socket最大的区别在于读和写都可以在一个buffer中完成,而不需要使用一个输入流和一个输出流,但是目前并不是一个非阻塞模式的Socket,要想使用非阻塞模式的socket需要从手动开启,修改代码:

private void start(){
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    SocketChannel socketChannel = null;
    try {
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("localhost",7788));
        if (socketChannel.finishConnect()) {
            for (int i = 0; i < 3; i++) {
                String info = "这是第" + i + "条信息\n";
                buffer.clear();
                buffer.put(info.getBytes());
                buffer.flip();
                socketChannel.write(buffer);
                buffer.clear();
                socketChannel.read(buffer);
                buffer.flip();
                System.out.println(new String(buffer.array(), 0, buffer.limit()));
            }
        }
        socketChannel.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (socketChannel != null){
            try {
                socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


使用channel.configureBlocking(false)来实现非阻塞的信道,在非阻塞式信道上调用一个方法总是会立即返回。这种调用的返回值指示了所请求的操作完成的程度。例如,在一个非阻塞式ServerSocketChannel上调用accept()方法,如果有连接请求来了,则返回客户端SocketChannel,否则返回null。但是看运行的结果,发现少了一条服务器的回复,这是因为整个channel变为非阻塞了,在进行读取的时候,是不需要等待服务器进行回复就会返回结果的,即socketChannel.read(buffer)方法在读取信息的时候,不会等待数据真的传递过来,而是总会立刻返回结果,当读取的时候,恰好服务器还没有返回数据,那么buffer中就会为空,修改代码

private void start(){
    // 读写分别使用不同的Buffer
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
    SocketChannel socketChannel = null;
    try {
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("localhost",7788));
        if (socketChannel.finishConnect()) {
            for (int i = 0; i < 3; i++) {
                //写
                String info = "这是第" + i + "条信息\n";
                buffer.clear();
                buffer.put(info.getBytes());
                buffer.flip();
                socketChannel.write(buffer);
                //读
                readBuffer.compact(); //不丢弃掉未读取的消息
                socketChannel.read(readBuffer);
                readBuffer.flip();
                System.out.println(new String(buffer.array(), 0, readBuffer.limit()));
            }
        }
        socketChannel.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (socketChannel != null){
            try {
                socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


为读写操作分别准备不同的Buffer,这样可以在读数据的时候使用compact()来保证为读到的消息不会被清空

4. TCP服务器

根据之前的客户端案例,并没有体会到NIO的好处,这是因为无论是TCP-Client还是文件的读写并没有使用到多线程,NIO中最核心的还是在原始需要多线程的环境中可以不使用多线程来完成,这就涉及到Selector类,Selector类可以用于避免使用阻塞式客户端中很浪费资源的“忙等”方法。例如,考虑一个IM服务器。像QQ或者旺旺这样的,可能有几万甚至几千万个客户端同时连接到了服务器,但在任何时刻都只是非常少量的消息。

需要读取和分发。这就需要一种方法阻塞等待,直到至少有一个信道可以进行I/O操作,并指出是哪个信道。NIO的选择器就实现了这样的功能。一个Selector实例可以同时检查一组信道的I/O状态。用专业术语来说,选择器就是一个多路开关选择器,因为一个选择器能够管理多个信道上的I/O操作。然而如果用传统的方式来处理这么多客户端,使用的方法是循环地一个一个地去检查所有的客户端是否有I/O操作,如果当前客户端有I/O操作,则可能把当前客户端扔给一个线程池去处理,如果没有I/O操作则进行下一个轮询,当所有的客户端都轮询过了又接着从头开始轮询;这种方法是非常笨而且也非常浪费资源,因为大部分客户端是没有I/O操作,我们也要去检查;而Selector就不一样了,它在内部可以同时管理多个I/O,当一个信道有I/O操作的时候,他会通知Selector,Selector就是记住这个信道有I/O操作,并且知道是何种I/O操作,是读呢?是写呢?还是接受新的连接;所以如果使用Selector,它返回的结果只有两种结果,一种是0,即在你调用的时刻没有任何客户端需要I/O操作,另一种结果是一组需要I/O操作的客户端,这是你就根本不需要再检查了,因为它返回给你的肯定是你想要的。这样一种通知的方式比那种主动轮询的方式要高效得多!

要使用选择器(Selector),需要创建一个Selector实例(使用静态工厂方法open())并将其注册(register)到想要监控的信道上(注意,这要通过channel的方法实现,而不是使用selector的方法)。最后,调用选择器的select()方法。该方法会阻塞等待,直到有一个或更多的信道准备好了I/O操作或等待超时。select()方法将返回可进行I/O操作的信道数量。现在,在一个单独的线程中,通过调用select()方法就能检查多个信道是否准备好进行I/O操作。如果经过一段时间后仍然没有信道准备好,select()方法就会返回0,并允许程序继续执行其他任务。

使用NIO来改写TCP服务器:

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.Set;

public class NIOServer {
    Selector selector = null;
    ServerSocketChannel server = null;
    public static final int BUF_SIZE = 1024;

    public static void main(String[] args) {
        NIOServer server = new NIOServer();
        server.start();
    }

    private void handleAccept(SelectionKey key) {
        System.out.println("handleAccept");
        ServerSocketChannel ssChannel = (ServerSocketChannel) key.channel();
        try {
            SocketChannel socket = ssChannel.accept();
            socket.configureBlocking(false);
            socket.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(BUF_SIZE));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleRead(SelectionKey key) {
        System.out.println("handleRead");
        SocketChannel socketChannel = (SocketChannel) key.channel();
        ByteBuffer buf = (ByteBuffer) key.attachment();
        try {
            int read = socketChannel.read(buf);
            while (read > 0) {
                buf.flip();
                System.out.println(new String(buf.array(), 0, read));
                read = socketChannel.read(buf);
            }
            if (read == -1) {
                socketChannel.close();
                key.channel();
            } else {
                //read = 0 代表数据发送完成
                // 注册写操作
                socketChannel.register(selector, SelectionKey.OP_WRITE, ByteBuffer.allocate(BUF_SIZE));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleWrite(SelectionKey key) throws IOException {
        System.out.println("handleWrite");
        ByteBuffer buf = (ByteBuffer) key.attachment();
        buf.clear();
        buf.put("Echo".getBytes());
        buf.flip();
        SocketChannel sc = (SocketChannel) key.channel();
        while (buf.hasRemaining()) {
            sc.write(buf);
        }
        // 对同一个channel进行注册会将之前注册的操作符取消
        sc.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(BUF_SIZE));

    }

    private void start() {


        try {
            selector = Selector.open();
            server = ServerSocketChannel.open();
            server.bind(new InetSocketAddress("localhost", 7789));
            server.configureBlocking(false);//非阻塞
            server.register(selector, SelectionKey.OP_ACCEPT);//注册accept事件

            while (true) {
                System.out.println("阻塞");
                selector.select();//阻塞,直到有注册过的channel可以使用
                System.out.println("in");
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    System.out.println("---");
                    int op = selectionKey.readyOps();
                    switch (op) {
                        case SelectionKey.OP_READ:
                            handleRead(selectionKey);
                            break;
                        case SelectionKey.OP_WRITE:
                            handleWrite(selectionKey);
                            break;
                        case SelectionKey.OP_ACCEPT:
                            handleAccept(selectionKey);
                            break;
                        default:
                    }
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ServerSocketChannel

ServerSocketChannel 对应着ServerSocket,使用方法也大致与ServerSocket相同,不过可以开启信道并切换为非阻塞模式

Selector

Selector是非阻塞服务器的核心,使用静态方法Selector selector = Selector.open()进行创建,为了将Channel和Selector配合使用,必须将Channel注册到Selector上,通过channel.register()方法来实现

ssc= ServerSocketChannel.open();
           ssc.socket().bind(new InetSocketAddress(PORT));
           ssc.configureBlocking(false);
           ssc.register(selector, SelectionKey.OP_ACCEPT);

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

注意register()方法的第二个参数。这是一个“interest集合”,意思是在通过Selector监听Channel时对什么事件感兴趣。可以监听四种不同类型的事件,并用常量表示:
- Connect : SelectionKey.OP_CONNECT
- Accept : SelectionKey.OP_ACCEPT
- Read : SelectionKey.OP_READ
- Write : SelectionKey.OP_WRITE

通道触发了一个事件意思是该事件已经就绪。所以,某个channel成功连接到另一个服务器称为“连接就绪”。一个server socket channel准备好接收新进入的连接称为“接收就绪”。一个有数据可读的通道可以说是“读就绪”。等待写数据的通道可以说是“写就绪”。

SelectionKey

当向Selector注册Channel时,register()方法会返回一个SelectionKey对象,这个对象包含了我们可能会用到的一些属性:

interest集合

interest集合可以用来获取向select中注册事件

int inserestSet = selectionKey.interestOps();

返回值是一个int类型,而注册的事件也都是int类型的常亮,可以通过按位与操作,来确定某个事件是否注册

boolean isInterestedInAccept  = (interestSet & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT;
boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT;
boolean isInterestedInRead    = interestSet & SelectionKey.OP_READ;
boolean isInterestedInWrite   = interestSet & SelectionKey.OP_WRITE;
ready集合

ready 集合是通道已经准备就绪的操作的集合。在一次选择(Selection)之后,你会首先访问这个ready set。

int readySet = selectionKey.readyOps();

可以像监测interest集合那样的方法,来检测channel中什么事件或操作已经就绪。但是,也可以使用以下四个方法,它们都会返回一个布尔类型:

selectionKey.isAcceptable();
selectionKey.isConnectable();
selectionKey.isReadable();
selectionKey.isWritable();
Channel和selector

从SelectionKey访问Channel和Selector很简单。如下:

Channel  channel  = selectionKey.channel();
Selector selector = selectionKey.selector();
附加的对象(可选)

可以将一个对象或者更多信息附着到SelectionKey上,这样就能方便的识别某个给定的通道。例如,可以附加 与通道一起使用的Buffer,或是包含聚集数据的某个对象。使用方法如下:

selectionKey.attach(theObject);
Object attachedObj = selectionKey.attachment();

还可以在用register()方法向Selector注册Channel的时候附加对象。如:

SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);

通过Selector选择通道

一旦向Selector注册了一或多个通道,就可以调用几个重载的select()方法。这些方法返回你所感兴趣的事件(如连接、接受、读或写)已经准备就绪的那些通道。换句话说,如果你对“读就绪”的通道感兴趣,select()方法会返回读事件已经就绪的那些通道。
select()方法有三个:

  • int select()
  • int select(long timeout)
  • int selectNow()

select()阻塞到至少有一个通道在你注册的事件上就绪了。
select(long timeout)和select()一样,除了最长会阻塞timeout毫秒(参数)。
selectNow()不会阻塞,不管什么通道就绪都立刻返回(译者注:此方法执行非阻塞的选择操作。如果自从前一次选择操作后,没有通道变成可选择的,则此方法直接返回零。)。

select()方法返回的int值表示有多少通道已经就绪。亦即,自上次调用select()方法后有多少通道变成就绪状态。如果调用select()方法,因为有一个通道变成就绪状态,返回了1,若再次调用select()方法,如果另一个通道就绪了,它会再次返回1。如果对第一个就绪的channel没有做任何操作,现在就有两个就绪的通道,但在每次select()方法调用之间,只有一个通道就绪了。

一旦调用了select()方法,并且返回值表明有一个或更多个通道就绪了,然后可以通过调用selector的selectedKeys()方法,访问“已选择键集(selected key set)”中的就绪通道。如下所示:

Set selectedKeys = selector.selectedKeys();

当像Selector注册Channel时,Channel.register()方法会返回一个SelectionKey 对象。这个对象代表了注册到该Selector的通道。可以通过SelectionKey的selectedKeySet()方法访问这些对象。

注意每次迭代末尾的keyIterator.remove()调用。Selector不会自己从已选择键集中移除SelectionKey实例。必须在处理完通道时自己移除。下次该通道变成就绪时,Selector会再次将其放入已选择键集中。

SelectionKey.channel()方法返回的通道需要转型成你要处理的类型,如ServerSocketChannel或SocketChannel等。

5. 内存映射文件

FileChannel提供了map方法来把文件影射为内存映像文件: MappedByteBuffer map(int mode,long position,long size); 可以把文件的从position开始的size大小的区域映射为内存映像文件,mode指出了 可访问该内存映像文件的方式:

  • READ_ONLY,(只读): 试图修改得到的缓冲区将导致抛出 ReadOnlyBufferException.(MapMode.READ_ONLY)
  • READ_WRITE(读/写): 对得到的缓冲区的更改最终将传播到文件;该更改对映射到同一文件的其他程序不一定是可见的。 (MapMode.READ_WRITE)
  • PRIVATE(专用): 对得到的缓冲区的更改不会传播到文件,并且该更改对映射到同一文件的其他程序也不是可见的;相反,会创建缓冲区已修改部分的专用副本。 (MapMode.PRIVATE)

MappedByteBuffer是ByteBuffer的子类,其扩充了三个方法:
- force():缓冲区是READ_WRITE模式下,此方法对缓冲区内容的修改强行写入文件;
- load():将缓冲区的内容载入内存,并返回该缓冲区的引用;
- isLoaded():如果缓冲区的内容在物理内存中,则返回真,否则返回假;

对比复制文件的速度

package com.lanou3g;

import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Date;

public class LargeFile {


    public static void copyBIO(String src, String desc) {
        long startTime = System.currentTimeMillis();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            File srcFile = new File(src);
            File descFile = new File(desc);
            descFile.createNewFile();

            bis = new BufferedInputStream(new FileInputStream(srcFile));
            bos = new BufferedOutputStream(new FileOutputStream(descFile));
            byte[] buf = new byte[2048 *1024];
            int len = 0;
            while ((len = bis.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        long time = System.currentTimeMillis() - startTime;
        System.out.println(time + "ms");
    }

    public static void copy(String src, String desc) {
        long startTime = System.currentTimeMillis();
        FileChannel srcFC = null;
        FileChannel descFC = null;
        try {
            File srcFile = new File(src);
            File descFile = new File(desc);
            descFile.createNewFile();
            srcFC = new FileInputStream(srcFile).getChannel();
            descFC = new FileOutputStream(descFile).getChannel();

            MappedByteBuffer mbb = srcFC.map(FileChannel.MapMode.READ_ONLY, 0, srcFile.length());

            descFC.write(mbb);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (srcFC != null) {
                try {
                    srcFC.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (descFC != null) {
                try {
                    descFC.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long time = System.currentTimeMillis() - startTime;
        System.out.println(time + "ms");
    }

    public static void main(String[] args) {
        copy("src/android-studio-ide-171.4443003-windows.exe", "src/a.exe");
        copyBIO("src/android-studio-ide-171.4443003-windows.exe", "src/b.exe");

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值