Sets {@link io.grpc.Channel} and {@link io.netty.channel.EventLoopGroup} to Nio. A major
benefit over using setters is gRPC will manage the life cycle of {@link
io.netty.channel.EventLoopGroup}.
504353
public static void useNioTransport(NettyChannelBuilder builder) {
    builder.channelType(NioSocketChannel.class);
    builder
        .eventLoopGroupPool(SharedResourcePool.forResource(Utils.NIO_WORKER_EVENT_LOOP_GROUP));
  }
321038
protected <T> void setEventNotifier(Class<T> eventSet, T notifier)
    {
        _notifiers.put(eventSet,notifier);

        //
        // Register this notifier for all EventSet interfaces up the interface inheritance
        // hiearachy as well
        //
        List<Class> superEventSets = new ArrayList<Class>();
        getSuperEventSets(eventSet, superEventSets);
        Iterator<Class> i = superEventSets.iterator();
        while (i.hasNext())
        {
            Class superEventSet = i.next();
            _notifiers.put(superEventSet,notifier);
        }
    }
1317445
public void addHttp2ClientChannel(EventLoop eventLoop, HttpRoute httpRoute, Http2ClientChannel http2ClientChannel) {
        if (!eventLoops.contains(eventLoop)) {
            eventLoops.add(eventLoop);
        }
        final EventLoopPool eventLoopPool = getOrCreateEventLoopPool(eventLoop);
        String key = generateKey(httpRoute);
        final EventLoopPool.PerRouteConnectionPool perRouteConnectionPool = getOrCreatePerRoutePool(eventLoopPool, key);
        perRouteConnectionPool.addChannel(http2ClientChannel);

        // Configure a listener to remove connection from pool when it is closed
        http2ClientChannel.getChannel().closeFuture().
            addListener(future -> {
                            EventLoopPool.PerRouteConnectionPool pool = eventLoopPool.fetchPerRoutePool(key);
                            if (pool != null) {
                                pool.removeChannel(http2ClientChannel);
                                http2ClientChannel.getDataEventListeners().
                                    forEach(Http2DataEventListener::destroy);
                            }
                        }
            );
    }
82076
public <T> GrpcServerBuilder withChildOption(ChannelOption<T> option, T value) {
    mNettyServerBuilder = mNettyServerBuilder.withChildOption(option, value);
    return this;
  }
353297
public ChannelFuture leaveGroup(InetAddress multicastAddress,
                                    NetworkInterface networkInterface, InetAddress source) {
        if (DetectionUtil.javaVersion() < 7) {
            throw new UnsupportedOperationException();
        } else {
            if (multicastAddress == null) {
                throw new NullPointerException("multicastAddress");
            }

            if (networkInterface == null) {
                throw new NullPointerException("networkInterface");
            }

            synchronized (this) {
                if (memberships != null) {
                    List<MembershipKey> keys = memberships.get(multicastAddress);
                    if (keys != null) {
                        Iterator<MembershipKey> keyIt = keys.iterator();

                        while (keyIt.hasNext()) {
                            MembershipKey key = keyIt.next();
                            if (networkInterface.equals(key.networkInterface())) {
                                if (source == null && key.sourceAddress() == null ||
                                        source != null && source.equals(key.sourceAddress())) {
                                    key.drop();
                                    keyIt.remove();
                                }
                            }
                        }
                        if (keys.isEmpty()) {
                            memberships.remove(multicastAddress);
                        }
                    }
                }
            }
            return succeededFuture(this);
        }
    }
642294
public void setEventCategoryGroupList(java.util.Collection<EventCategoryGroup> eventCategoryGroupList) {
        if (eventCategoryGroupList == null) {
            this.eventCategoryGroupList = null;
            return;
        }

        this.eventCategoryGroupList = new java.util.ArrayList<EventCategoryGroup>(eventCategoryGroupList);
    }
1170748
public EpollSocketChannelConfig setTcpCork(boolean tcpCork) {
        try {
            ((EpollSocketChannel) channel).socket.setTcpCork(tcpCork);
            return this;
        } catch (IOException e) {
            throw new ChannelException(e);
        }
    }
557841
protected boolean setConnector() {
		if (this.host == null) {
			log.error("No host value set, cannot set up socket connector.");
			return false;
		}
		if (this.port < 0 || this.port > 65535) {
			log.error("Port value is invalid {}.", Integer.valueOf(this.port));
			return false;
		}
		if (this.executors == null) {
			this.executors = new ExecutorFilter(1);
		}
		this.connector = new NioSocketConnector();
		this.connector.getSessionConfig().setWriterIdleTime(
				SolverWorldModelInterface.TIMEOUT_PERIOD /2);
		this.connector.getSessionConfig().setReaderIdleTime(
				(int) Math.ceil(TIMEOUT_PERIOD * 1.1));
		if (!this.connector.getFilterChain().contains(
				WorldModelSolverProtocolCodecFactory.CODEC_NAME)) {
			this.connector.getFilterChain().addLast(
					WorldModelSolverProtocolCodecFactory.CODEC_NAME,
					new ProtocolCodecFilter(
							new WorldModelSolverProtocolCodecFactory(true)));
		}
		this.connector.getFilterChain().addLast("ExecutorPool", this.executors);
		this.connector.setHandler(this.ioHandler);
		log.debug("Connector set up successful.");
		return true;
	}
305508
public void setup(ExecutorType clientExecutor,
                    ExecutorType serverExecutor,
                    MessageSize requestSize,
                    MessageSize responseSize,
                    FlowWindowSize windowSize,
                    ChannelType channelType,
                    int maxConcurrentStreams,
                    int channelCount) throws Exception {
    NettyServerBuilder serverBuilder;
    NettyChannelBuilder channelBuilder;
    if (channelType == ChannelType.LOCAL) {
      LocalAddress address = new LocalAddress("netty-e2e-benchmark");
      serverBuilder = NettyServerBuilder.forAddress(address);
      serverBuilder.channelType(LocalServerChannel.class);
      channelBuilder = NettyChannelBuilder.forAddress(address);
      channelBuilder.channelType(LocalChannel.class);
    } else {
      ServerSocket sock = new ServerSocket();
      // Pick a port using an ephemeral socket.
      sock.bind(new InetSocketAddress(BENCHMARK_ADDR, 0));
      SocketAddress address = sock.getLocalSocketAddress();
      sock.close();
      serverBuilder = NettyServerBuilder.forAddress(address);
      channelBuilder = NettyChannelBuilder.forAddress(address);
    }

    if (serverExecutor == ExecutorType.DIRECT) {
      serverBuilder.directExecutor();
    }
    if (clientExecutor == ExecutorType.DIRECT) {
      channelBuilder.directExecutor();
    }

    // Always use a different worker group from the client.
    ThreadFactory serverThreadFactory = new DefaultThreadFactory("STF pool", true /* daemon */);
    serverBuilder.workerEventLoopGroup(new NioEventLoopGroup(0, serverThreadFactory));

    // Always set connection and stream window size to same value
    serverBuilder.flowControlWindow(windowSize.bytes());
    channelBuilder.flowControlWindow(windowSize.bytes());

    channelBuilder.negotiationType(NegotiationType.PLAINTEXT);
    serverBuilder.maxConcurrentCallsPerConnection(maxConcurrentStreams);

    // Create buffers of the desired size for requests and responses.
    PooledByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;
    // Use a heap buffer for now, since MessageFramer doesn't know how to directly convert this
    // into a WritableBuffer
    // TODO(carl-mastrangelo): convert this into a regular buffer() call.  See
    // https://github.com/grpc/grpc-java/issues/2062#issuecomment-234646216
    request = alloc.heapBuffer(requestSize.bytes());
    request.writerIndex(request.capacity() - 1);
    response = alloc.heapBuffer(responseSize.bytes());
    response.writerIndex(response.capacity() - 1);

    // Simple method that sends and receives NettyByteBuf
    unaryMethod = MethodDescriptor.<ByteBuf, ByteBuf>newBuilder()
        .setType(MethodType.UNARY)
        .setFullMethodName("benchmark/unary")
        .setRequestMarshaller(new ByteBufOutputMarshaller())
        .setResponseMarshaller(new ByteBufOutputMarshaller())
        .build();

    pingPongMethod = unaryMethod.toBuilder()
        .setType(MethodType.BIDI_STREAMING)
        .setFullMethodName("benchmark/pingPong")
        .build();
    flowControlledStreaming = pingPongMethod.toBuilder()
        .setFullMethodName("benchmark/flowControlledStreaming")
        .build();

    // Server implementation of unary & streaming methods
    serverBuilder.addService(
        ServerServiceDefinition.builder(
            new ServiceDescriptor("benchmark",
                unaryMethod,
                pingPongMethod,
                flowControlledStreaming))
            .addMethod(unaryMethod, new ServerCallHandler<ByteBuf, ByteBuf>() {
                  @Override
                  public ServerCall.Listener<ByteBuf> startCall(
                      final ServerCall<ByteBuf, ByteBuf> call,
                      Metadata headers) {
                    call.sendHeaders(new Metadata());
                    call.request(1);
                    return new ServerCall.Listener<ByteBuf>() {
                      @Override
                      public void onMessage(ByteBuf message) {
                        // no-op
                        message.release();
                        call.sendMessage(response.slice());
                      }

                      @Override
                      public void onHalfClose() {
                        call.close(Status.OK, new Metadata());
                      }

                      @Override
                      public void onCancel() {

                      }

                      @Override
                      public void onComplete() {
                      }
                    };
                  }
                })
            .addMethod(pingPongMethod, new ServerCallHandler<ByteBuf, ByteBuf>() {
                  @Override
                  public ServerCall.Listener<ByteBuf> startCall(
                      final ServerCall<ByteBuf, ByteBuf> call,
                      Metadata headers) {
                    call.sendHeaders(new Metadata());
                    call.request(1);
                    return new ServerCall.Listener<ByteBuf>() {
                      @Override
                      public void onMessage(ByteBuf message) {
                        message.release();
                        call.sendMessage(response.slice());
                        // Request next message
                        call.request(1);
                      }

                      @Override
                      public void onHalfClose() {
                        call.close(Status.OK, new Metadata());
                      }

                      @Override
                      public void onCancel() {

                      }

                      @Override
                      public void onComplete() {

                      }
                    };
                  }
                })
            .addMethod(flowControlledStreaming, new ServerCallHandler<ByteBuf, ByteBuf>() {
                  @Override
                  public ServerCall.Listener<ByteBuf> startCall(
                      final ServerCall<ByteBuf, ByteBuf> call,
                      Metadata headers) {
                    call.sendHeaders(new Metadata());
                    call.request(1);
                    return new ServerCall.Listener<ByteBuf>() {
                      @Override
                      public void onMessage(ByteBuf message) {
                        message.release();
                        while (call.isReady()) {
                          call.sendMessage(response.slice());
                        }
                        // Request next message
                        call.request(1);
                      }

                      @Override
                      public void onHalfClose() {
                        call.close(Status.OK, new Metadata());
                      }

                      @Override
                      public void onCancel() {

                      }

                      @Override
                      public void onComplete() {

                      }

                      @Override
                      public void onReady() {
                        while (call.isReady()) {
                          call.sendMessage(response.slice());
                        }
                      }
                    };
                  }
                })
            .build());

    // Build and start the clients and servers
    server = serverBuilder.build();
    server.start();
    channels = new ManagedChannel[channelCount];
    ThreadFactory clientThreadFactory = new DefaultThreadFactory("CTF pool", true /* daemon */);
    for (int i = 0; i < channelCount; i++) {
      // Use a dedicated event-loop for each channel
      channels[i] = channelBuilder
          .eventLoopGroup(new NioEventLoopGroup(1, clientThreadFactory))
          .build();
    }
  }
940457
public void set(Collection<Builder> channels) throws ChannelFinderException {
		wrappedSubmit(new SetChannels(ChannelUtil.toCollectionXmlChannels(channels)));
	}
415597
public static void useNioTransport(NettyServerBuilder builder) {
    builder.channelType(NioServerSocketChannel.class);
    builder
        .bossEventLoopGroupPool(SharedResourcePool.forResource(Utils.NIO_BOSS_EVENT_LOOP_GROUP));
    builder
        .workerEventLoopGroupPool(
            SharedResourcePool.forResource(Utils.NIO_WORKER_EVENT_LOOP_GROUP));
  }
251789
private EventLoopResources eventLoopResources(EventLoop eventLoop) {
    EventLoopResources resources = eventLoopResources.get();
    if (resources == null) {
      resources = new EventLoopResources(eventLoop);
      eventLoopResources.set(resources);
    }
    return resources;
  }
356650
public final UdpServer runOn(EventLoopGroup eventLoopGroup) {
		Objects.requireNonNull(eventLoopGroup, "eventLoopGroup");
		return runOn(preferNative -> eventLoopGroup);
	}
30754
private void buildChannel() {
      FileLookup fileLookup = FileLookupFactory.newInstance();

      // in order of preference - we first look for an external JGroups file, then a set of XML
      // properties, and
      // finally the legacy JGroups String properties.
      String cfg;
      if (props != null) {
         if (props.containsKey(CHANNEL_LOOKUP)) {
            String channelLookupClassName = props.getProperty(CHANNEL_LOOKUP);

            try {
               JGroupsChannelLookup lookup = Util.getInstance(channelLookupClassName, configuration.classLoader());
               channel = lookup.getJGroupsChannel(props);
               connectChannel = lookup.shouldConnect();
               disconnectChannel = lookup.shouldDisconnect();
               closeChannel = lookup.shouldClose();
            } catch (ClassCastException e) {
               log.wrongTypeForJGroupsChannelLookup(channelLookupClassName, e);
               throw new CacheException(e);
            } catch (Exception e) {
               log.errorInstantiatingJGroupsChannelLookup(channelLookupClassName, e);
               throw new CacheException(e);
            }
         }

         if (channel == null && props.containsKey(CHANNEL_CONFIGURATOR)) {
            JGroupsChannelConfigurator configurator = (JGroupsChannelConfigurator) props.get(CHANNEL_CONFIGURATOR);
            try {
               channel = configurator.createChannel();
            } catch (Exception e) {
               throw log.errorCreatingChannelFromConfigurator(configurator.getProtocolStackString(), e);
            }
         }

         if (channel == null && props.containsKey(CONFIGURATION_FILE)) {
            cfg = props.getProperty(CONFIGURATION_FILE);
            Collection<URL> confs = Collections.emptyList();
            try {
               confs = fileLookup.lookupFileLocations(cfg, configuration.classLoader());
            } catch (IOException io) {
               //ignore, we check confs later for various states
            }
            if (confs.isEmpty()) {
               throw log.jgroupsConfigurationNotFound(cfg);
            } else if (confs.size() > 1) {
               log.ambiguousConfigurationFiles(Util.toStr(confs));
            }
            try {
               channel = new JChannel(confs.iterator().next());
            } catch (Exception e) {
               throw log.errorCreatingChannelFromConfigFile(cfg, e);
            }
         }

         if (channel == null && props.containsKey(CONFIGURATION_XML)) {
            cfg = props.getProperty(CONFIGURATION_XML);
            try {
               channel = new JChannel(XmlConfigHelper.stringToElement(cfg));
            } catch (Exception e) {
               throw log.errorCreatingChannelFromXML(cfg, e);
            }
         }

         if (channel == null && props.containsKey(CONFIGURATION_STRING)) {
            cfg = props.getProperty(CONFIGURATION_STRING);
            try {
               channel = new JChannel(new ByteArrayInputStream(cfg.getBytes()));
            } catch (Exception e) {
               throw log.errorCreatingChannelFromConfigString(cfg, e);
            }
         }
      }

      if (channel == null) {
         log.unableToUseJGroupsPropertiesProvided(props);
         try {
            channel = new JChannel(
                  fileLookup.lookupFileLocation(DEFAULT_JGROUPS_CONFIGURATION_FILE, configuration.classLoader()));
         } catch (Exception e) {
            throw log.errorCreatingChannelFromConfigFile(DEFAULT_JGROUPS_CONFIGURATION_FILE, e);
         }
      }
   }
133589
public <T> void set(EventLocal<T> key, Object value) {
        EventLocalMap<EventLocal<?>, Object> map = getMap(key);
        if (null == map) {
            // the call to getMap would have created the inheritable map
            // if appropriate, thus always create a disconnected map here
            map = new EventLocalMap<EventLocal<?>, Object>();
            if (key.isInheritable()) {
                this.inheritableLocals = map;
            } else {
                this.locals = map;
            }
        }
        map.put(key, value);
    }
1372305
@Handler
    public void onNioRegistration(NioRegistration event)
            throws IOException {
        SelectableChannel channel = event.ioChannel();
        channel.configureBlocking(false);
        SelectionKey key;
        synchronized (selectorGate) {
            selector.wakeup(); // make sure selector isn't blocking
            key = channel.register(
                selector, event.ops(), event.handler());
        }
        event.setResult(new Registration(key));
    }
133623
public <T> AioClient setOption(SocketOption<T> name, T value) throws IOException {
		this.session.getChannel().setOption(name, value);
		return this;
	}