简体   繁体   English

Java中Selector的优势是什么

[英]What's the advantage of Selector in Java

As I know we can register all SocketChannels into one single Selector on the server side, but why? 据我所知,我们可以将所有SocketChannel注册到服务器端的一个选择器中,但是为什么呢? It's there any difference with adding these SocketChannels into a ArrayList, then I iterate this List manually? 将这些SocketChannel添加到ArrayList中有什么区别,然后我手动迭代此List?

Selectors provide low-latency transfer of control. 选择器提供了低延迟的控制传递。 If you periodically wake up and walk a list of channels, then your average latency is T/2, and the only way to reduce that is to spend more time walking the list;for very small T you're effectively busy looping. 如果您定期唤醒并浏览频道列表,则平均等待时间为T / 2,减少此延迟的唯一方法是花更多时间浏览列表;对于很小的T,您实际上忙于循环。 With a selector, the average latency is smaller and there's no cycles wasted maintaining or walking the list. 使用选择器,平均延迟更短,并且不会浪费任何时间维护或遍历列表。

Selectors allow the JVM implementation to work efficiently with the operating systems select/epoll/kqueue (or equivalent) mechanism by pushing the work down into the appropriate kernel/driver. 通过将工作下推到适当的内核/驱动程序中,选择器允许JVM实现与操作系统的select / epoll / kqueue(或等效方法)机制一起有效地工作。 The modern OS implementation of such functions is generally considered to be O(1). 这种功能的现代OS实现通常被认为是O(1)。

That is, Java itself can "sleep" until the underlying OS signals one or more channels - which is configured and reported in Java NIO via Selectors. 也就是说,Java本身可以“休眠”,直到底层OS发出一个或多个通道的信号为止-这是通过选择器在Java NIO中配置和报告的。

When in a loop with the Selector, select will "block" until there is a channel change - so keeping with the Selectors allows one to efficiently find the relevant channels and handle them. 与选择器循环时,选择将“阻止”直到发生频道更改-因此与选择器保持一致可以使人们有效地找到相关的频道并进行处理。 It's all part of the above goal to keep the "per-event" processing O(c), where c << n, when dealing with n channels. 上述目标的全部都是在处理n个通道时保持“按事件”处理O(c),其中c << n。

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

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