Java IO vs NIO,真正的区别是什么?

kev*_*ind 6 java io networking nio netty

我非常喜欢Java NIO,我真的想将Java NIO应用到我当前的系统中,但是当我创建这些示例应用程序来比较Java IO和NIO时,它让我非常失望.

这是我的2个样本(我没有把所有的源代码)

Java IO

public class BlockingServerClient {

    private static final Logger log = Logger.getLogger(BlockingServerClient.class.getName());

    static final ExecutorService service = Executors.newCachedThreadPool();

    public static void main(String[] args) throws InterruptedException {
        int port = Integer.parseInt(args[0]);

        BlockingServerClient server = new BlockingServerClient();

        Server sr = server.new Server(port);
        service.submit(sr);
    }

    private class Server implements Runnable {

        .....

        public void run() {
            ServerSocket ss = null;
            try {
                ss = new ServerSocket(localPort);
                log.info("Server socket bound to " + localPort);

                while (true) {
                    Socket client = ss.accept();
                    log.info("Accepted connection from " + client.getRemoteSocketAddress());

                    service.submit(new SocketClient(client));
                }

            } catch (IOException e) {
                log.log(Level.SEVERE, "Server error", e);
            } finally {
                .....
            }
        }
    }

    private class SocketClient implements Runnable {

        .....

        public void run() {
            InetSocketAddress addr = (InetSocketAddress) socket.getRemoteSocketAddress();
            socketInfo = String.format("%s:%s", addr.getHostName(), addr.getPort());

            log.info("Start reading data from " + socketInfo);
            try {
                in = new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));

                String input;
                while ((input = in.readLine()) != null) {
                    log.info(String.format("[%s] %s", socketInfo, input));

                    log.info("Socket " + socketInfo + " thread sleep 4s");
                    TimeUnit.SECONDS.sleep(4);
                }

            } catch (Exception ex) {
                log.log(Level.SEVERE, "Socket error", ex);
            } finally {
                .....
            }
        }
    }   
}
Run Code Online (Sandbox Code Playgroud)

Java NIO

public class NonBlockingServerClient {

    private static final Logger log = Logger.getLogger(NonBlockingServerClient.class.getName());

    public static void main(String[] args) {
        int port = Integer.parseInt(args[0]);

        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            NonBlockingServerClient sc = new NonBlockingServerClient();

            Server server = sc.new Server(port, boss, worker);

            server.run();

        } catch (Exception e) {
            log.log(Level.SEVERE, "Error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    private class Server {

        .....

        public void run() {
            log.info("Start Server bootstrap");
            ServerBootstrap b = new ServerBootstrap();
            b.group(boss, worker)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipe = ch.pipeline();
                    pipe.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                    pipe.addLast(new StringDecoder());
                    pipe.addLast(new ClientHandler());
                }
            });

            ChannelFuture future = null;
            try {
                future = b.bind(port).sync();
                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                log.log(Level.SEVERE, "Server binding error", e);
                future.channel().close();
            }

        }
    }

    private class ClientHandler extends SimpleChannelInboundHandler<String> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg)
                throws Exception {
            log.info(String.format("[%s] %s", ctx.channel().remoteAddress(), msg));
            log.info(ctx.channel().remoteAddress() + " sleep 4s");
            TimeUnit.SECONDS.sleep(4);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

客户

public class Client {

    private static final Logger log = Logger.getLogger(Client.class.getName());

    public static void main(String[] args) throws InterruptedException {
        int port = Integer.parseInt(args[0]);

        for (int i = 0; i < 10; i++) {
            Client cl = new Client("localhost", port);
            cl.start();
            TimeUnit.MILLISECONDS.sleep(500);
        }
    }

    String host;
    int port;

    public Client(String host, int port) {
        this.host = host;
        this.port =port;
    }

    public void start() {
        log.info("Start client running");
        Socket socket = null;
        String info = "";
        try {
            socket = new Socket(host, port);
            InetSocketAddress addr = (InetSocketAddress) socket.getLocalSocketAddress();
            info = String.format("%s:%s", addr.getHostName(), addr.getPort());
            int count = 10;

            OutputStream out = socket.getOutputStream();
            while (count > 0) {
                String outStr = "Output-" + count + "\n";
                out.write(outStr.getBytes());
                out.flush();
                count--;
            }
            out.write((info + "-Finish sending").getBytes());
            out.flush();
        } catch (Exception e) {
            log.log(Level.SEVERE, "Client error", e);
        } finally {
            try {
                socket.close();
                log.info(info + "-Client close");
            } catch (IOException e) {
                log.log(Level.SEVERE, "Closing client error", e);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

运行时客户端将创建10个连接到服务器的客户端.在我多次运行和监控之后,我发现Java IO和NIO之间没有任何区别.

如果将客户端数量更改为500,我发现java IO确实创建了500个线程,但是数据的消耗确实很快.相比之下,java NIO应用程序的线程比另一个少得多,但数据的消耗很慢,并且需要更长的时间来完成所有操作.

那么,Java NIO的真正好处是什么?创建更少的线程以节省内存但性能更慢.

或者,我可能做错了.

Chr*_*s K 6

您注意到的速度差异是因为两个测试用例中都出现了4s睡眠.

在非NIO情况下,每个请求有一个线程,睡眠4秒只阻止一个请求.但是,在NIO情况下,工作线程的数量要少得多,它会阻止该请求以及等待在该线程上运行的所有其他请求.

所以这就引出了一个问题,为什么我们希望在NIO方法中使用更少的线程?答案是可扩展性.现代操作系统存在与网络IO上阻塞的线程数相关的扩展问题.有关详细信息,请参阅C10K问题.

一般来说,我发现NIO更快,或者至少它有可能更快,如果:

  1. 您可以使用它来避免复制缓冲区
  2. 而你避免任何可以阻止线程的东西.例如,不要阻止数据库提取等.

这就是像akka这样的异步框架闪耀的地方.