简体   繁体   English

Java NIO 中的阻塞和非阻塞模式

[英]Blocking and Non-Blocking Modes in Java NIO

I'm self-taught Java and I'm a bit confused when implementing this functionality of Java NIO.我是自学的 Java,在实现 Java NIO 的这个功能时我有点困惑。 I am confused about Java NIO's blocking mode.我对 Java NIO 的阻塞模式感到困惑。 Is the purpose of setting non-blocking mode to be for the selector to detect that the channel is ready for I/O operations?设置非阻塞模式的目的是为了让选择器检测通道已准备好进行 I/O 操作吗? And assuming mode is set to "true" will the selector detect the channel or not?并假设模式设置为“真”,选择器是否会检测到通道? Hoping someone can explain it to me, give me sample code or any suggestions I would be very grateful.希望有人可以向我解释,给我示例代码或任何建议,我将不胜感激。 Thanks very much非常感谢

public class NioServer {

public void start() throws IOException {

    Selector selector = Selector.open();

    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

    serverSocketChannel.bind(new InetSocketAddress(8000));

    // configureBlocking is problem
    serverSocketChannel.configureBlocking(false);
    ....
    }

In Blocking mode when client communicates with the server call such as send, receive, connect(TCP only) and accept(TCP only) will block indefinitely until that operation is performed.在阻塞模式下,当客户端与服务器调用通信时,例如发送、接收、连接(仅限 TCP)和接受(仅限 TCP)将无限期地阻塞,直到执行该操作。 On the other hand in Non Blocking mode these functions will return immediately.另一方面,在非阻塞模式下,这些函数将立即返回。

For example, when a client invokes the read() method to read data from the server, the thread gets blocked until the data is available.例如,当客户端调用 read() 方法从服务器读取数据时,线程会被阻塞,直到数据可用。 This situation is undesirable under some circumstances.这种情况在某些情况下是不可取的。 Instead, what we can do is use the waiting period to do some other task.相反,我们可以做的是利用等待时间来做一些其他的任务。 The client socket then can notify when the data is available.然后,客户端套接字可以在数据可用时发出通知。 Another problem is that, in a multi-socket connection, each client is a separate thread.另一个问题是,在多套接字连接中,每个客户端都是一个单独的线程。 Therefore, there is an overhead of maintaining a pool of client threads.因此,存在维护客户端线程池的开销。

Now to answer your question, you can control whether you want Blocking or Non Blocking mode in your application.现在回答您的问题,您可以在应用程序中控制是否需要阻塞或非阻塞模式。 If you set like below如果你设置如下

  serverSocketChannel.configureBlocking(false);

then server will run in Non Blocking mode otherwise it will run in Blocking mode by default.然后服务器将以非阻塞模式运行,否则默认以阻塞模式运行。

Here are some articles for refernece这里有一些文章供参考

  1. Blocking and Non-Blocking Sockets 阻塞和非阻塞 Sockets
  2. Non-blocking Socket Programming in Java Java中的非阻塞套接字编程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM