java - 关于Java ServerSocket接受: busy-wating?

标签 java serversocket

我正在阅读 Java 中的 TCP/IP 套接字,关于服务器套接字,它说

When we call accept() on that ServerSocket instance, if a new connection is pending, accept() returns immediately; otherwise it blocks until either a connection comes in or the timer expires, whichever comes first. This allows a single thread to handle multiple connections. Unfortunately, the approach requires that we constantly poll all sources of I/O, and that kind of “busy waiting” approach again introduces a lot of overhead from cycling through connections just to find out that they have nothing to do.

据我了解,当连接到来时是否应该“通知”,因此不应该“忙等待”?我是不是误会了什么……?

-----------------编辑----------------------

全文如下:

Because of these complications, some programmers prefer to stick with a single-threaded approach, in which the server has only one thread, which deals with all clients—not sequentially, but all at once. Such a server cannot afford to block on an I/O operation with any one client, and must use nonblocking I/O exclusively. Recall that with nonblocking I/O, we specify the maximum amount of time that a call to an I/O method may block (including zero). We saw an example of this in Chapter 4, where we set a timeout on the accept operation (via the setSoTimeout() method of ServerSocket). When we call accept() on that ServerSocket instance, if a new connection is pending, accept() returns immediately; otherwise it blocks until either a connection comes in or the timer expires, whichever comes first. This allows a single thread to handle multiple connections. Unfortunately, the approach requires that we constantly poll all sources of I/O, and that kind of “busy waiting” approach again introduces a lot of overhead from cycling through connections just to find out that they have nothing to do

最佳答案

即使在整个引文中,这也大多是无稽之谈。 或者您正在使用阻塞 I/O,在这种情况下,您需要每个连接一个线程,并且每个 receive() 循环需要另一个线程,或者您正在使用非阻塞 I/O,在这种情况下,您可以使用 Java 7 中的 select(),或者,您正在使用异步 I/O,在这种情况下,所有回调都是完成处理程序。在这些情况下,您都不需要轮询或忙等待。

认为他一定是指使用具有非常短的超时时间的阻塞模式,但这确实是最不清楚的。

关于java - 关于Java ServerSocket接受: busy-wating?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22419813/

相关文章:

java - 在 Hibernate 中映射枚举子类型

java - Spring 3.0 : SQL not committed when exception is thrown

java - 从托管 bean 事件 JSF 重定向

java - 创建服务器,保持服务运行(或阻塞?)的技术

java - 在java中处理异常而不导致服务器套接字崩溃?

java - 从 Camel 路由在 ActiveMQ 上强制套接字超时?

java - 如何使用主类中的方法从嵌套类返回泛型类型

java - 服务器接受大量持久的客户端连接

Java套接字客户端连接和断开问题

java - 自建http服务器无法处理postman请求