【问题标题】:Java IO vs NIO, what is really difference?Java IO vs NIO,真正的区别是什么?
【发布时间】:2014-07-07 14:48:17
【问题描述】:

我非常喜欢 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 {
                .....
            }
        }
    }   
}

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);
        }

    }
}

客户

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);
            }
        }
    }
}

客户端在运行时将创建 10 个客户端连接到服务器。跑了几次,监控了几次,发现Java IO和NIO没什么区别。

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

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

或者,我可能做错了。

【问题讨论】:

    标签: java networking io netty nio


    【解决方案1】:

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

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

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

    总的来说,我确实发现 NIO 更快,或者至少在以下情况下它有可能更快:

    1. 您使用它来避免复制缓冲区
    2. 并且避免任何可能阻塞线程的事情。例如不要阻止 在数据库提取等方面。

    这就是像 akka 这样的异步框架大放异彩的地方。

    【讨论】:

    • here提到的,NIO-非阻塞IO,是一种单线程编程模型,内部涉及select()系统调用。我不确定,为什么我们将线程阻塞 IO 与线程 NIO 进行比较。
    猜你喜欢
    • 1970-01-01
    • 2017-06-02
    • 2012-02-16
    • 2020-01-02
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2015-02-16
    • 2014-08-20
    相关资源
    最近更新 更多