if (PlatformDependent.javaVersion() >= 9 && PlatformDependent.hasUnsafe()) { // Let us try to use sun.misc.Unsafe to replace the SelectionKeySet. // This allows us to also do this in Java9+ without any extra flags. longselectedKeysFieldOffset= PlatformDependent.objectFieldOffset(selectedKeysField); longpublicSelectedKeysFieldOffset= PlatformDependent.objectFieldOffset(publicSelectedKeysField);
if (selectedKeysFieldOffset != -1 && publicSelectedKeysFieldOffset != -1) { PlatformDependent.putObject(unwrappedSelector, selectedKeysFieldOffset, selectedKeySet); PlatformDependent.putObject(unwrappedSelector, publicSelectedKeysFieldOffset, selectedKeySet); returnnull; } // We could not retrieve the offset, lets try reflection as last-resort. }
/** * 将拿到的两个属性设置成可修改的 */ Throwablecause= ReflectionUtil.trySetAccessible(selectedKeysField, true); if (cause != null) return cause; cause = ReflectionUtil.trySetAccessible(publicSelectedKeysField, true); if (cause != null) return cause;
// NioEventLoop.java privatebooleanunexpectedSelectorWakeup(int selectCnt) { if (Thread.interrupted()) { // Thread was interrupted so reset selected keys and break so we not run into a busy loop. // As this is most likely a bug in the handler of the user or it's client library we will // also log it. // // See https://github.com/netty/netty/issues/2426 returntrue; } if (SELECTOR_AUTO_REBUILD_THRESHOLD > 0 && selectCnt >= SELECTOR_AUTO_REBUILD_THRESHOLD) { // 判定发生空轮询 // The selector returned prematurely many times in a row. // Rebuild the selector to work around the problem. this.rebuildSelector(); returntrue; } returnfalse; }
try { // time to close the old selector as everything else is registered to the new one oldSelector.close(); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("Failed to close the old Selector.", t); } }
if (logger.isInfoEnabled()) { logger.info("Migrated " + nChannels + " channel(s) to the new Selector."); } }