while(true)ServerSocket侦听的效率 [英] Efficiency of while(true) ServerSocket Listen

查看:559
本文介绍了while(true)ServerSocket侦听的效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道典型的while(true) ServerSocket侦听循环是否需要整个内核来等待并接受客户端连接(即使在实现可运行并使用Thread .start()时)

I am wondering if a typical while(true) ServerSocket listen loop takes an entire core to wait and accept a client connection (Even when implementing runnable and using Thread .start())

我正在实现一种分布式计算集群,每台计算机都需要它具有的每个核心来进行计算.主节点需要与这些计算机通信(调用修改算法功能的静态方法).

I am implementing a type of distributed computing cluster and each computer needs every core it has for computation. A Master node needs to communicate with these computers (invoking static methods that modify the algorithm's functioning).

我需要使用套接字的原因是由于具有跨平台/跨语言功能.在某些情况下,PHP将调用这些Java静态方法.

The reason I need to use sockets is due to the cross platform / cross language capabilities. In some cases, PHP will be invoking these java static methods.

我使用了一个Java事件探查器(YourKit),可以看到正在运行的ServerSocket侦听线程,它从不休眠,并且始终在运行.是否有更好的方法来做我想做的事?还是性能影响可以忽略不计?

I used a java profiler (YourKit) and I can see my running ServerSocket listen thread and it never sleeps and it's always running. Is there a better approach to do what I want? Or, will the performance hit be negligible?

如果您能想到更好的方法,请随时提出任何建议(我已经尝试过RMI,但不支持跨语言.

Please, feel free to offer any suggestion if you can think of a better way (I've tried RMI, but it isn't supported cross-language.

谢谢大家

推荐答案

如果您的意思是这样的话:

If you mean something like this:

while (true) {
  Socket socket = server.accept();
  /* Do something with socket... */
}

然后,不,对accept()的调用不会占用整个核心".这是一个阻塞调用,它将允许为另一个线程调度CPU,直到客户端实际连接为止.一旦返回对accept()的调用,将安排当前线程运行并消耗CPU,直到它在循环的下一次迭代中在accept()上阻塞为止.

then, no, the call to accept() does not "take an entire core." It's a blocking call that will allow the CPU to be scheduled for another thread until a client actually connects. Once the call to accept() returns, the current thread will be scheduled to run and will consume CPU until it blocks on accept() in the next iteration of the loop.

为避免其他客户端的侦听积压太大,通常使用另一个线程与新接受的Socket进行交互,而让一个线程专注于接受新客户端.套接字处理线程可能会使用NIO处理多个套接字,或者可能专用于单个套接字,这虽然编写起来简单得多,但却无法很好地扩展成百上千个并发连接.

To avoid the listen backlog of other clients growing too large, another thread usually handles interaction with the newly-accepted Socket, leaving one thread to focus on accepting new clients. The socket handling thread might handle many sockets, using NIO, or it might be dedicated to a single socket, which is much simpler to code but won't scale well past many hundreds of simultaneous connections.

这篇关于while(true)ServerSocket侦听的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆