Example usage for io.netty.util.concurrent DefaultThreadFactory DefaultThreadFactory

List of usage examples for io.netty.util.concurrent DefaultThreadFactory DefaultThreadFactory

Introduction

In this page you can find the example usage for io.netty.util.concurrent DefaultThreadFactory DefaultThreadFactory.

Prototype

public DefaultThreadFactory(String poolName, int priority) 

Source Link

Usage

From source file:com.alibaba.dubbo.qos.server.Server.java

License:Apache License

/**
 * start server, bind port/*from  w  ww .  j a v a 2 s . c  om*/
 */
public void start() throws Throwable {
    if (!hasStarted.compareAndSet(false, true)) {
        return;
    }
    boss = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-boss", true));
    worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true));
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(boss, worker);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    serverBootstrap.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new QosProcessHandler(welcome, acceptForeignIp));
        }
    });
    try {
        serverBootstrap.bind(port).sync();
        logger.info("qos-server bind localhost:" + port);
    } catch (Throwable throwable) {
        logger.error("qos-server can not bind localhost:" + port, throwable);
        throw throwable;
    }
}

From source file:com.alibaba.dubbo.remoting.transport.netty.NettyServer.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    //netty4/*from   w ww . jav  a 2  s  .c om*/
    bootstrap = new ServerBootstrap();
    //1?
    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    //       cpu*2 
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            //                
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}

From source file:com.alibaba.dubbo.remoting.transport.netty4.NettyServer.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();

    bootstrap = new ServerBootstrap();

    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override//from   w  w w .ja va2s.co  m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}

From source file:com.couchbase.client.core.CouchbaseCore.java

License:Apache License

/**
 * Creates a new {@link CouchbaseCore}./*from  w  ww . j  a v a 2  s . c om*/
 */
public CouchbaseCore(final CoreEnvironment environment) {
    LOGGER.info(environment.toString());
    LOGGER.debug(Diagnostics.collectAndFormat());

    this.environment = environment;
    configProvider = new DefaultConfigurationProvider(this, environment);
    ThreadFactory disruptorThreadFactory = new DefaultThreadFactory("cb-core", true);
    responseDisruptor = new Disruptor<ResponseEvent>(new ResponseEventFactory(),
            environment.responseBufferSize(), disruptorThreadFactory);
    responseDisruptor.setDefaultExceptionHandler(new ExceptionHandler<ResponseEvent>() {
        @Override
        public void handleEventException(Throwable ex, long sequence, ResponseEvent event) {
            LOGGER.warn("Exception while Handling Response Events {}", event, ex);
        }

        @Override
        public void handleOnStartException(Throwable ex) {
            LOGGER.warn("Exception while Starting Response RingBuffer", ex);
        }

        @Override
        public void handleOnShutdownException(Throwable ex) {
            LOGGER.info("Exception while shutting down Response RingBuffer", ex);
        }
    });
    responseDisruptor.handleEventsWith(new ResponseHandler(environment, this, configProvider));
    responseDisruptor.start();
    RingBuffer<ResponseEvent> responseRingBuffer = responseDisruptor.getRingBuffer();

    requestDisruptor = new Disruptor<RequestEvent>(new RequestEventFactory(), environment.requestBufferSize(),
            disruptorThreadFactory, ProducerType.MULTI,
            environment.requestBufferWaitStrategy().newWaitStrategy());
    requestHandler = new RequestHandler(environment, configProvider.configs(), responseRingBuffer);
    requestDisruptor.setDefaultExceptionHandler(new ExceptionHandler<RequestEvent>() {
        @Override
        public void handleEventException(Throwable ex, long sequence, RequestEvent event) {
            LOGGER.warn("Exception while Handling Request Events {}", event, ex);
        }

        @Override
        public void handleOnStartException(Throwable ex) {
            LOGGER.warn("Exception while Starting Request RingBuffer", ex);
        }

        @Override
        public void handleOnShutdownException(Throwable ex) {
            LOGGER.info("Exception while shutting down Request RingBuffer", ex);
        }
    });
    requestDisruptor.handleEventsWith(requestHandler);
    requestDisruptor.start();
    requestRingBuffer = requestDisruptor.getRingBuffer();
}

From source file:com.couchbase.client.core.env.DefaultCoreEnvironment.java

License:Apache License

protected DefaultCoreEnvironment(final Builder builder) {
    if (++instanceCounter > MAX_ALLOWED_INSTANCES) {
        LOGGER.warn("More than " + MAX_ALLOWED_INSTANCES + " Couchbase Environments found (" + instanceCounter
                + "), this can have severe impact on performance and stability. Reuse environments!");
    }//from   w  ww.j av a  2 s . c  om
    dcpEnabled = booleanPropertyOr("dcpEnabled", builder.dcpEnabled);
    sslEnabled = booleanPropertyOr("sslEnabled", builder.sslEnabled);
    sslKeystoreFile = stringPropertyOr("sslKeystoreFile", builder.sslKeystoreFile);
    sslKeystorePassword = stringPropertyOr("sslKeystorePassword", builder.sslKeystorePassword);
    bootstrapHttpEnabled = booleanPropertyOr("bootstrapHttpEnabled", builder.bootstrapHttpEnabled);
    bootstrapHttpDirectPort = intPropertyOr("bootstrapHttpDirectPort", builder.bootstrapHttpDirectPort);
    bootstrapHttpSslPort = intPropertyOr("bootstrapHttpSslPort", builder.bootstrapHttpSslPort);
    bootstrapCarrierEnabled = booleanPropertyOr("bootstrapCarrierEnabled", builder.bootstrapCarrierEnabled);
    bootstrapCarrierDirectPort = intPropertyOr("bootstrapCarrierDirectPort",
            builder.bootstrapCarrierDirectPort);
    bootstrapCarrierSslPort = intPropertyOr("bootstrapCarrierSslPort", builder.bootstrapCarrierSslPort);
    int ioPoolSize = intPropertyOr("ioPoolSize", builder.ioPoolSize);
    int computationPoolSize = intPropertyOr("computationPoolSize", builder.computationPoolSize);
    responseBufferSize = intPropertyOr("responseBufferSize", builder.responseBufferSize);
    requestBufferSize = intPropertyOr("requestBufferSize", builder.requestBufferSize);
    dcpConnectionBufferSize = intPropertyOr("dcpConnectionBufferSize", builder.dcpConnectionBufferSize);
    dcpConnectionBufferAckThreshold = doublePropertyOr("dcpConnectionBufferAckThreshold",
            builder.dcpConnectionBufferAckThreshold);
    dcpConnectionName = stringPropertyOr("dcpConnectionName", builder.dcpConnectionName);
    kvServiceEndpoints = intPropertyOr("kvEndpoints", builder.kvEndpoints);
    viewServiceEndpoints = intPropertyOr("viewEndpoints", builder.viewEndpoints);
    queryServiceEndpoints = intPropertyOr("queryEndpoints", builder.queryEndpoints);
    searchServiceEndpoints = intPropertyOr("searchEndpoints", builder.searchEndpoints);
    packageNameAndVersion = stringPropertyOr("packageNameAndVersion", builder.packageNameAndVersion);
    userAgent = stringPropertyOr("userAgent", builder.userAgent);
    observeIntervalDelay = builder.observeIntervalDelay;
    reconnectDelay = builder.reconnectDelay;
    retryDelay = builder.retryDelay;
    retryStrategy = builder.retryStrategy;
    maxRequestLifetime = longPropertyOr("maxRequestLifetime", builder.maxRequestLifetime);
    keepAliveInterval = longPropertyOr("keepAliveInterval", builder.keepAliveInterval);
    autoreleaseAfter = longPropertyOr("autoreleaseAfter", builder.autoreleaseAfter);
    bufferPoolingEnabled = booleanPropertyOr("bufferPoolingEnabled", builder.bufferPoolingEnabled);
    tcpNodelayEnabled = booleanPropertyOr("tcpNodelayEnabled", builder.tcpNodelayEnabled);
    mutationTokensEnabled = booleanPropertyOr("mutationTokensEnabled", builder.mutationTokensEnabled);
    socketConnectTimeout = intPropertyOr("socketConnectTimeout", builder.socketConnectTimeout);
    callbacksOnIoPool = booleanPropertyOr("callbacksOnIoPool", builder.callbacksOnIoPool);
    disconnectTimeout = longPropertyOr("disconnectTimeout", builder.disconnectTimeout);
    sslKeystore = builder.sslKeystore;

    if (ioPoolSize < MIN_POOL_SIZE) {
        LOGGER.info("ioPoolSize is less than {} ({}), setting to: {}", MIN_POOL_SIZE, ioPoolSize,
                MIN_POOL_SIZE);
        this.ioPoolSize = MIN_POOL_SIZE;
    } else {
        this.ioPoolSize = ioPoolSize;
    }

    if (computationPoolSize < MIN_POOL_SIZE) {
        LOGGER.info("computationPoolSize is less than {} ({}), setting to: {}", MIN_POOL_SIZE,
                computationPoolSize, MIN_POOL_SIZE);
        this.computationPoolSize = MIN_POOL_SIZE;
    } else {
        this.computationPoolSize = computationPoolSize;
    }

    if (builder.ioPool == null) {
        this.ioPool = new NioEventLoopGroup(ioPoolSize(), new DefaultThreadFactory("cb-io", true));
        this.ioPoolShutdownHook = new IoPoolShutdownHook(this.ioPool);
    } else {
        this.ioPool = builder.ioPool;
        this.ioPoolShutdownHook = builder.ioPoolShutdownHook == null ? new NoOpShutdownHook()
                : builder.ioPoolShutdownHook;
    }

    if (!(this.ioPoolShutdownHook instanceof NoOpShutdownHook)) {
        this.nettyShutdownHook = new NettyShutdownHook();
    } else {
        this.nettyShutdownHook = this.ioPoolShutdownHook;
    }

    if (builder.scheduler == null) {
        CoreScheduler managed = new CoreScheduler(computationPoolSize());
        this.coreScheduler = managed;
        this.coreSchedulerShutdownHook = managed;
    } else {
        this.coreScheduler = builder.scheduler;
        this.coreSchedulerShutdownHook = builder.schedulerShutdownHook == null ? new NoOpShutdownHook()
                : builder.schedulerShutdownHook;
    }
    this.eventBus = builder.eventBus == null ? new DefaultEventBus(coreScheduler) : builder.eventBus;
    this.runtimeMetricsCollector = new RuntimeMetricsCollector(eventBus, coreScheduler,
            builder.runtimeMetricsCollectorConfig == null ? DefaultMetricsCollectorConfig.create()
                    : builder.runtimeMetricsCollectorConfig);
    this.networkLatencyMetricsCollector = new NetworkLatencyMetricsCollector(eventBus, coreScheduler,
            builder.networkLatencyMetricsCollectorConfig == null ? DefaultLatencyMetricsCollectorConfig.create()
                    : builder.networkLatencyMetricsCollectorConfig);

    if (builder.defaultMetricsLoggingConsumer != null) {
        metricsCollectorSubscription = eventBus.get().filter(new Func1<CouchbaseEvent, Boolean>() {
            @Override
            public Boolean call(CouchbaseEvent evt) {
                return evt.type().equals(EventType.METRIC);
            }
        }).subscribe(builder.defaultMetricsLoggingConsumer);
    } else {
        metricsCollectorSubscription = null;
    }

    if (builder.requestBufferWaitStrategy == null) {
        requestBufferWaitStrategy = new WaitStrategyFactory() {
            @Override
            public WaitStrategy newWaitStrategy() {
                return new BlockingWaitStrategy();
            }
        };
    } else {
        requestBufferWaitStrategy = builder.requestBufferWaitStrategy;
    }
}

From source file:com.github.milenkovicm.kafka.KafkaProducer.java

License:Apache License

public KafkaProducer(String hostname, int port, String topicName, ProducerProperties properties) {
    this(hostname, port, topicName, properties,
            new NioEventLoopGroup(properties.get(ProducerProperties.NETTY_THREAD_COUNT),
                    new DefaultThreadFactory("producer-" + topicName, Thread.MAX_PRIORITY)));
}

From source file:com.lambdaworks.redis.resource.DefaultEventLoopGroupProvider.java

License:Apache License

/**
 * Create an instance of a {@link EventExecutorGroup}. Supported types are:
 * <ul>// ww w .j a  va  2s .  c o  m
 * <li>DefaultEventExecutorGroup</li>
 * <li>NioEventLoopGroup</li>
 * <li>EpollEventLoopGroup</li>
 * </ul>
 * 
 * @param type the type
 * @param numberOfThreads the number of threads to use for the {@link EventExecutorGroup}
 * @param <T> type parameter
 * @return a new instance of a {@link EventExecutorGroup}
 * @throws IllegalArgumentException if the {@code type} is not supported.
 */
public static <T extends EventExecutorGroup> EventExecutorGroup createEventLoopGroup(Class<T> type,
        int numberOfThreads) {

    if (DefaultEventExecutorGroup.class.equals(type)) {
        return new DefaultEventExecutorGroup(numberOfThreads,
                new DefaultThreadFactory("lettuce-eventExecutorLoop", true));
    }

    if (NioEventLoopGroup.class.equals(type)) {
        return new NioEventLoopGroup(numberOfThreads, new DefaultThreadFactory("lettuce-nioEventLoop", true));
    }

    if (EpollProvider.isAvailable() && EpollProvider.isEventLoopGroup(type)) {
        return EpollProvider.newEventLoopGroup(numberOfThreads,
                new DefaultThreadFactory("lettuce-epollEventLoop", true));
    }

    throw new IllegalArgumentException("Type " + type.getName() + " not supported");
}

From source file:com.linecorp.armeria.client.NonDecoratingClientFactory.java

License:Apache License

protected NonDecoratingClientFactory(SessionOptions options) {
    this(options, type -> {
        switch (type) {
        case NIO:
            return new DefaultThreadFactory("armeria-client-nio", false);
        case EPOLL:
            return new DefaultThreadFactory("armeria-client-epoll", false);
        default:/*from   w ww  .  ja  v a2s . c o m*/
            throw new Error();
        }
    });
}

From source file:com.linecorp.armeria.common.util.EventLoopGroups.java

License:Apache License

/**
 * Returns a newly-created {@link EventLoopGroup}.
 *
 * @param numThreads the number of event loop threads
 * @param threadNamePrefix the prefix of thread names
 * @param useDaemonThreads whether to create daemon threads or not
 *///  w ww  .java 2 s .  c  o  m
public static EventLoopGroup newEventLoopGroup(int numThreads, String threadNamePrefix,
        boolean useDaemonThreads) {

    checkArgument(numThreads > 0, "numThreads: %s (expected: > 0)", numThreads);
    requireNonNull(threadNamePrefix, "threadNamePrefix");

    final TransportType type = TransportType.detectTransportType();
    final String prefix = threadNamePrefix + '-' + type.lowerCasedName();
    return newEventLoopGroup(numThreads, new DefaultThreadFactory(prefix, useDaemonThreads));
}

From source file:com.linecorp.armeria.server.GracefulShutdownHandlerTest.java

License:Apache License

@Before
public void setUp() {
    executor = new ThreadPoolExecutor(0, 1, 1, TimeUnit.SECONDS, new LinkedTransferQueue<>(),
            new DefaultThreadFactory(GracefulShutdownHandlerTest.class, true));

    handler = new GracefulShutdownHandler(Duration.ofNanos(QUIET_PERIOD_NANOS), executor, ticker);
}