سؤال

As I know we can register all SocketChannels into one single Selector on the server side, but why? It's there any difference with adding these SocketChannels into a ArrayList, then I iterate this List manually?

هل كانت مفيدة؟

المحلول

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. The modern OS implementation of such functions is generally considered to be 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.

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.

نصائح أخرى

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. With a selector, the average latency is smaller and there's no cycles wasted maintaining or walking the list.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top