io.netty.util.HashedWheelTimer Java Examples

The following examples show how to use io.netty.util.HashedWheelTimer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NettyHttpClient.java    From mpush with Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart(Listener listener) throws Throwable {
    workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
    b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new HttpResponseDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast("encoder", new HttpRequestEncoder());
            ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
        }
    });
    timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
    listener.onSuccess();
}
 
Example #2
Source File: MasterSlaveConnectionManager.java    From redisson with Apache License 2.0 6 votes vote down vote up
protected void initTimer(MasterSlaveServersConfig config) {
    int[] timeouts = new int[]{config.getRetryInterval(), config.getTimeout()};
    Arrays.sort(timeouts);
    int minTimeout = timeouts[0];
    if (minTimeout % 100 != 0) {
        minTimeout = (minTimeout % 100) / 2;
    } else if (minTimeout == 100) {
        minTimeout = 50;
    } else {
        minTimeout = 100;
    }
    
    timer = new HashedWheelTimer(new DefaultThreadFactory("redisson-timer"), minTimeout, TimeUnit.MILLISECONDS, 1024, false);
    
    connectionWatcher = new IdleConnectionWatcher(this, config);
    subscribeService = new PublishSubscribeService(this, config);
}
 
Example #3
Source File: BKNamespaceDriver.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
private BookKeeperClientBuilder createBKCBuilder(String bkcName,
                                                 DistributedLogConfiguration conf,
                                                 String zkServers,
                                                 String ledgersPath,
                                                 EventLoopGroup eventLoopGroup,
                                                 HashedWheelTimer requestTimer,
                                                 Optional<FeatureProvider> featureProviderOptional,
                                                 StatsLogger statsLogger) {
    BookKeeperClientBuilder builder = BookKeeperClientBuilder.newBuilder()
            .name(bkcName)
            .dlConfig(conf)
            .zkServers(zkServers)
            .ledgersPath(ledgersPath)
            .eventLoopGroup(eventLoopGroup)
            .requestTimer(requestTimer)
            .featureProvider(featureProviderOptional)
            .statsLogger(statsLogger);
    LOG.info("Created shared client builder {} : zkServers = {}, ledgersPath = {}, numIOThreads = {}",
            new Object[] { bkcName, zkServers, ledgersPath, conf.getBKClientNumberIOThreads() });
    return builder;
}
 
Example #4
Source File: TopicDoesNotExistsTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateProducerOnNotExistsTopic() throws PulsarClientException, InterruptedException {
    PulsarClient pulsarClient = PulsarClient.builder().serviceUrl(lookupUrl.toString()).build();
    try {
        pulsarClient.newProducer()
                .topic("persistent://public/default/" + UUID.randomUUID().toString())
                .sendTimeout(100, TimeUnit.MILLISECONDS)
                .create();
        Assert.fail("Create producer should failed while topic does not exists.");
    } catch (PulsarClientException ignore) {
    }
    Thread.sleep(2000);
    HashedWheelTimer timer = (HashedWheelTimer) ((PulsarClientImpl) pulsarClient).timer();
    Assert.assertEquals(timer.pendingTimeouts(), 0);
    Assert.assertEquals(((PulsarClientImpl) pulsarClient).producersCount(), 0);
    pulsarClient.close();
}
 
Example #5
Source File: TopicDoesNotExistsTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateConsumerOnNotExistsTopic() throws PulsarClientException, InterruptedException {
    PulsarClient pulsarClient = newPulsarClient(lookupUrl.toString(), 1);
    try {
        pulsarClient.newConsumer()
                .topic("persistent://public/default/" + UUID.randomUUID().toString())
                .subscriptionName("test")
                .subscribe();
        Assert.fail("Create consumer should failed while topic does not exists.");
    } catch (PulsarClientException ignore) {
    }
    Thread.sleep(2000);
    HashedWheelTimer timer = (HashedWheelTimer) ((PulsarClientImpl) pulsarClient).timer();
    Assert.assertEquals(timer.pendingTimeouts(), 0);
    Assert.assertEquals(((PulsarClientImpl) pulsarClient).consumersCount(), 0);
}
 
Example #6
Source File: ServerTest.java    From simulacron with Apache License 2.0 6 votes vote down vote up
@Test
public void testTryWithResourcesShouldCloseAllClustersButNotTimerIfProvided() throws Exception {
  EventLoopGroup eventLoop;
  Timer timer = new HashedWheelTimer();

  try (Server server = Server.builder().withTimer(timer).build()) {
    // Do nothing here, since this is a unit test, we don't want to create any inet sockets
    // which is what Server does by default.
    eventLoop = server.eventLoopGroup;
  }

  // event loop should have been closed since a custom one was not provided.
  assertThat(eventLoop.isShutdown()).isTrue();
  // timer should not have been closed since a custom one was provided.
  timer.newTimeout(
      timeout -> {
        // noop
      },
      1,
      TimeUnit.SECONDS);
  timer.stop();
}
 
Example #7
Source File: DnsNamingService.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
public DnsNamingService(BrpcURL namingUrl) {
    Validate.notNull(namingUrl);
    Validate.notEmpty(namingUrl.getHostPorts());
    this.namingUrl = namingUrl;

    String[] splits = namingUrl.getHostPorts().split(":");
    this.host = splits[0];
    if (splits.length == 2) {
        this.port = Integer.valueOf(splits[1]);
    } else {
        this.port = 80;
    }
    this.hostPort = this.host + ":" + this.port;
    this.updateInterval = namingUrl.getIntParameter(
            Constants.INTERVAL, Constants.DEFAULT_INTERVAL);
    namingServiceTimer = new HashedWheelTimer(new CustomThreadFactory("namingService-timer-thread"));
}
 
Example #8
Source File: PulsarClientImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public PulsarClientImpl(ClientConfigurationData conf, EventLoopGroup eventLoopGroup, ConnectionPool cnxPool)
        throws PulsarClientException {
    if (conf == null || isBlank(conf.getServiceUrl()) || eventLoopGroup == null) {
        throw new PulsarClientException.InvalidConfigurationException("Invalid client configuration");
    }
    this.eventLoopGroup = eventLoopGroup;
    setAuth(conf);
    this.conf = conf;
    this.clientClock = conf.getClock();
    conf.getAuthentication().start();
    this.cnxPool = cnxPool;
    externalExecutorProvider = new ExecutorProvider(conf.getNumListenerThreads(), getThreadFactory("pulsar-external-listener"));
    if (conf.getServiceUrl().startsWith("http")) {
        lookup = new HttpLookupService(conf, eventLoopGroup);
    } else {
        lookup = new BinaryProtoLookupService(this, conf.getServiceUrl(), conf.getListenerName(), conf.isUseTls(), externalExecutorProvider.getExecutor());
    }
    timer = new HashedWheelTimer(getThreadFactory("pulsar-timer"), 1, TimeUnit.MILLISECONDS);
    producers = Maps.newIdentityHashMap();
    consumers = Maps.newIdentityHashMap();
    state.set(State.Open);
}
 
Example #9
Source File: ProducerStatsRecorderImplTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncrementNumAcksReceived() throws Exception {
    ClientConfigurationData conf = new ClientConfigurationData();
    conf.setStatsIntervalSeconds(1);
    PulsarClientImpl client = mock(PulsarClientImpl.class);
    when(client.getConfiguration()).thenReturn(conf);
    Timer timer = new HashedWheelTimer();
    when(client.timer()).thenReturn(timer);
    ProducerImpl<?> producer = mock(ProducerImpl.class);
    when(producer.getTopic()).thenReturn("topic-test");
    when(producer.getProducerName()).thenReturn("producer-test");
    when(producer.getPendingQueueSize()).thenReturn(1);
    ProducerConfigurationData producerConfigurationData = new ProducerConfigurationData();
    ProducerStatsRecorderImpl recorder = new ProducerStatsRecorderImpl(client, producerConfigurationData, producer);
    long latencyNs = TimeUnit.SECONDS.toNanos(1);
    recorder.incrementNumAcksReceived(latencyNs);
    Thread.sleep(1200);
    assertEquals(1000.0, recorder.getSendLatencyMillisMax(), 0.5);
}
 
Example #10
Source File: ReflexController.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Inject
@SuppressWarnings("null")
public ReflexController(
   ReflexLocalProcessing localProcessing,
   ZigbeeLocalProcessing zigbee,
   ZWaveLocalProcessing zwave,
   /*
   SercommLocalProcessing sercomm,
   */
   Router router
) {
   this.timer = new HashedWheelTimer();
   this.router = router;

   this.zigbee = zigbee;
   this.zwave = zwave;
   /*
   this.sercomm = sercomm;
   */
   this.localProcessing = localProcessing;

   this.pinToUser = new HashMap<>();
   this.userToPin = new HashMap<>();
   this.processors = new HashMap<>();
}
 
Example #11
Source File: BookKeeperClient.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
BookKeeperClient(DistributedLogConfiguration conf,
                 String name,
                 String zkServers,
                 ZooKeeperClient zkc,
                 String ledgersPath,
                 EventLoopGroup eventLoopGroup,
                 HashedWheelTimer requestTimer,
                 StatsLogger statsLogger,
                 Optional<FeatureProvider> featureProvider) {
    this.conf = conf;
    this.name = name;
    this.zkServers = zkServers;
    this.ledgersPath = ledgersPath;
    this.passwd = conf.getBKDigestPW().getBytes(UTF_8);
    this.eventLoopGroup = eventLoopGroup;
    this.requestTimer = requestTimer;
    this.statsLogger = statsLogger;
    this.featureProvider = featureProvider;
    this.ownZK = null == zkc;
    if (null != zkc) {
        // reference the passing zookeeper client
        this.zkc = zkc;
    }
}
 
Example #12
Source File: HomeGraphAPI.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Inject
public HomeGraphAPI(GoogleConfig config,
      GoogleRpcContext rpcContext,
      ProductCatalogManager prodCat,
      GoogleWhitelist whitelist,
      @Named(EXECUTOR_NAME) HashedWheelTimer executor
) {
   this.config = config;
   requestConfig = RequestConfig.custom()
      .setConnectionRequestTimeout(config.getConnectionRequestTimeoutMs())
      .setConnectTimeout(config.getConnectionTimeoutMs())
      .setSocketTimeout(config.getSocketTimeoutMs())
      .build();

   pool = new PoolingHttpClientConnectionManager(config.getTimeToLiveMs(), TimeUnit.MILLISECONDS);
   pool.setDefaultMaxPerRoute(config.getRouteMaxConnections());
   pool.setMaxTotal(config.getMaxConnections());
   pool.setValidateAfterInactivity(config.getValidateAfterInactivityMs());
   this.gRpcContext = rpcContext;
   this.prodCat = prodCat;
   this.whitelist = whitelist;
   this.executor = executor;
}
 
Example #13
Source File: GoogleCommandExecutor.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Inject
public GoogleCommandExecutor(
   @Named(VoiceConfig.NAME_EXECUTOR) ExecutorService executor,
   @Named(VoiceConfig.NAME_TIMEOUT_TIMER) HashedWheelTimer timeoutTimer,
   GoogleConfig config,
   CommandExecutor commandExecutor,
   GoogleWhitelist whitelist,
   ProductCatalogManager prodCat,
   Provider<VoiceContextExecutorRegistry> registry
) {
   this.executor = executor;
   this.timeoutTimer = timeoutTimer;
   this.config = config;
   this.commandExecutor = commandExecutor;
   this.whitelist = whitelist;
   this.prodCat = prodCat;
   this.registry = registry;
}
 
Example #14
Source File: SocketIOServer.java    From socketio with Apache License 2.0 6 votes vote down vote up
/**
 * Starts Socket.IO server with current configuration settings.
 *
 * @throws IllegalStateException
 *             if server already started
 */
public synchronized void start() {
  if (isStarted()) {
    throw new IllegalStateException("Failed to start Socket.IO server: server already started");
  }

  log.info("Socket.IO server starting");

  // Configure heartbeat scheduler
  timer = new HashedWheelTimer();
  timer.start();
  SocketIOHeartbeatScheduler.setHashedWheelTimer(timer);
  SocketIOHeartbeatScheduler.setHeartbeatInterval(configuration.getHeartbeatInterval());
  SocketIOHeartbeatScheduler.setHeartbeatTimeout(configuration.getHeartbeatTimeout());

  // Configure and bind server
  ServerBootstrapFactory bootstrapFactory = serverBootstrapFactory != null
      ? serverBootstrapFactory
      : new DefaultServerBootstrapFactory(configuration);
  bootstrap = bootstrapFactory.createServerBootstrap();
  bootstrap.childHandler(new SocketIOChannelInitializer(configuration, listener, pipelineModifier));
  bootstrap.bind(configuration.getPort()).syncUninterruptibly();

  state = State.STARTED;
  log.info("Socket.IO server started: {}", configuration);
}
 
Example #15
Source File: CommandExecutor.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Inject
public CommandExecutor(
   PlatformMessageBus bus,
   @Named(VoiceConfig.NAME_EXECUTOR) ExecutorService executor,
   VoiceConfig config,
   @Named(VoiceConfig.NAME_TIMEOUT_TIMER) HashedWheelTimer timeoutTimer,
   ResponseCompleter responseCompleter,
   PlacePopulationCacheManager populationCacheMgr
) {
   this.executor = executor;
   this.config = config;
   this.timeoutTimer = timeoutTimer;
   this.responseCompleter = responseCompleter;
   this.populationCacheMgr = populationCacheMgr;
   this.busClient = new PlatformBusClient(bus, executor, ImmutableSet.of(AddressMatchers.equals(Address.platformService(VoiceService.NAMESPACE))));
}
 
Example #16
Source File: AzureAsyncHttpClientUtils.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public static AsyncHttpClient newClient(final String accountName,
                                        final boolean isSecure,
                                        final HashedWheelTimer poolTimer) {
  final DefaultAsyncHttpClientConfig.Builder configBuilder = config()
    // TODO: Confirm a new thread pool is not getting created everytime
    .setThreadPoolName(accountName + "-azurestorage-async-client")
    .setChannelPool(new DefaultChannelPool(DEFAULT_IDLE_TIME, -1, poolTimer, DEFAULT_CLEANER_PERIOD))
    .setRequestTimeout(DEFAULT_REQUEST_TIMEOUT)
    .setResponseBodyPartFactory(AsyncHttpClientConfig.ResponseBodyPartFactory.LAZY)
    .setMaxRequestRetry(MAX_RETRIES);

  try {
    if (isSecure) {
      configBuilder.setSslContext(SslContextBuilder.forClient().build());
    }
  } catch (SSLException e) {
    logger.error("Error while setting ssl context in Async Client", e);
  }

  poolTimer.start();
  return asyncHttpClient(configBuilder.build());
}
 
Example #17
Source File: AlexaPlatformService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Inject
public AlexaPlatformService(AlexaPlatformServiceConfig config, PlatformMessageBus bus) {
   this.bus = bus;
   workerPool = new ThreadPoolBuilder()
      .withMaxPoolSize(config.getMaxListenerThreads())
      .withKeepAliveMs(config.getListenerThreadKeepAliveMs())
      .withNameFormat(DISPATCHER_POOL_NAME + "-%d")
      .withBlockingBacklog()
      .withMetrics("alexa.bridge")
      .build();
   timeoutPool = new HashedWheelTimer(new ThreadFactoryBuilder()
      .setDaemon(true)
      .setNameFormat(TIMEOUT_POOL_NAME + "-%d")
      .setUncaughtExceptionHandler(new LoggingUncaughtExceptionHandler(logger))
      .build());
   defaultTimeoutSecs = config.getDefaultTimeoutSecs();
}
 
Example #18
Source File: CompletableFutures.java    From Singularity with Apache License 2.0 6 votes vote down vote up
public static <T> CompletableFuture<T> enforceTimeout(
  CompletionStage<T> underlyingFuture,
  HashedWheelTimer timer,
  long timeout,
  TimeUnit timeUnit,
  Supplier<Exception> exceptionSupplier
) {
  // We don't want to muck with the underlying future passed in, so
  // chaining a .thenApply(x -> x) forces a new future to be created with its own
  // completion tracking. In this way, the original future is left alone and can
  // time out on its own schedule.
  CompletableFuture<T> future = underlyingFuture
    .thenApply(x -> x)
    .toCompletableFuture();
  Timeout hwtTimeout = timer.newTimeout(
    ignored -> future.completeExceptionally(exceptionSupplier.get()),
    timeout,
    timeUnit
  );
  future.whenComplete((result, throwable) -> hwtTimeout.cancel());
  return future;
}
 
Example #19
Source File: TestAzureStorageFileSystem.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceClosures() throws IOException {
  AsyncHttpClient asyncHttpClient = mock(AsyncHttpClient.class);
  PowerMockito.mockStatic(AzureAsyncHttpClientUtils.class);
  AtomicReference<HashedWheelTimer> timerInstance = new AtomicReference<>();
  when(AzureAsyncHttpClientUtils.newClient(eq(ACCOUNT), eq(true), any(HashedWheelTimer.class))).then(invocationOnMock -> {
    timerInstance.set(invocationOnMock.getArgument(2, HashedWheelTimer.class));
    return asyncHttpClient;
  });

  AzureStorageFileSystem azureStorageFileSystem = new AzureStorageFileSystem();
  azureStorageFileSystem.setup(getMockHadoopConf());

  // Close
  azureStorageFileSystem.close();

  verify(asyncHttpClient, times(1)).close();
  try {
    timerInstance.get().start();
    fail("Timer cannot be started if it was stopped properly at resource closure");
  } catch (IllegalStateException e) {
    assertEquals("cannot be started once stopped", e.getMessage());
  }
}
 
Example #20
Source File: TimeOutHandlerMgr.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static void init(int timeoutCheckerThreads) {
    timeoutCheckers = new RoundRobinPickerList<>(timeoutCheckerThreads);
    for (int i = 0; i < timeoutCheckerThreads; i++) {
        //1024*10ms = 10s for one wheel.
        HashedWheelTimer timeoutChecker = new HashedWheelTimer(
                new ThreadFactoryBuilder().setNameFormat("ServerTimeoutChecker-%d").setDaemon(true).build(),
                10, TimeUnit.MILLISECONDS, 1024);
        timeoutChecker.start();
        timeoutCheckers.add(timeoutChecker);
    }
    isInited = true;
}
 
Example #21
Source File: IdleStateChecker.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
public IdleStateChecker(
        HashedWheelTimer timer,
        long readerIdleTime,
        long writerIdleTime,
        long allIdleTime,
        TimeUnit unit) {

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

    this.timer = timer;

    if (readerIdleTime <= 0) {
        readerIdleTimeMillis = 0;
    } else {
        readerIdleTimeMillis = Math.max(unit.toMillis(readerIdleTime), MIN_TIMEOUT_MILLIS);
    }
    if (writerIdleTime <= 0) {
        writerIdleTimeMillis = 0;
    } else {
        writerIdleTimeMillis = Math.max(unit.toMillis(writerIdleTime), MIN_TIMEOUT_MILLIS);
    }
    if (allIdleTime <= 0) {
        allIdleTimeMillis = 0;
    } else {
        allIdleTimeMillis = Math.max(unit.toMillis(allIdleTime), MIN_TIMEOUT_MILLIS);
    }
}
 
Example #22
Source File: EtherNetIpClientConfig.java    From ethernet-ip with Apache License 2.0 5 votes vote down vote up
public EtherNetIpClientConfig(
    String hostname,
    int port,
    int vendorId,
    int serialNumber,
    Duration timeout,
    Duration maxIdle,
    int maxReconnectDelaySeconds,
    boolean lazy,
    boolean persistent,
    ExecutorService executor,
    ScheduledExecutorService scheduledExecutor,
    EventLoopGroup eventLoop,
    HashedWheelTimer wheelTimer,
    Consumer<Bootstrap> bootstrapConsumer,
    Map<String, String> loggingContext
) {

    this.hostname = hostname;
    this.port = port;
    this.vendorId = vendorId;
    this.serialNumber = serialNumber;
    this.timeout = timeout;
    this.maxIdle = maxIdle;
    this.maxReconnectDelaySeconds = maxReconnectDelaySeconds;
    this.lazy = lazy;
    this.persistent = persistent;
    this.executor = executor;
    this.scheduledExecutor = scheduledExecutor;
    this.eventLoop = eventLoop;
    this.wheelTimer = wheelTimer;
    this.bootstrapConsumer = bootstrapConsumer;
    this.loggingContext = loggingContext;
}
 
Example #23
Source File: ModbusTcpMasterConfig.java    From modbus with Apache License 2.0 5 votes vote down vote up
public ModbusTcpMasterConfig(
    String address,
    int port,
    Duration timeout,
    boolean lazy,
    boolean persistent,
    int maxReconnectDelay,
    String instanceId,
    ExecutorService executor,
    ScheduledExecutorService scheduler,
    EventLoopGroup eventLoop,
    HashedWheelTimer wheelTimer,
    Consumer<Bootstrap> bootstrapConsumer
) {

    this.address = address;
    this.port = port;
    this.timeout = timeout;
    this.lazy = lazy;
    this.persistent = persistent;
    this.maxReconnectDelay = maxReconnectDelay;
    this.instanceId = instanceId;
    this.executor = executor;
    this.scheduler = scheduler;
    this.eventLoop = eventLoop;
    this.wheelTimer = wheelTimer;
    this.bootstrapConsumer = bootstrapConsumer;
}
 
Example #24
Source File: TChannel.java    From tchannel-java with MIT License 5 votes vote down vote up
public Builder(@NotNull String service) {
    if (service == null) {
        throw new NullPointerException("`service` cannot be null");
    }

    this.service = service;
    this.host = TChannelUtilities.getCurrentIp();
    if (this.host == null) {
        logger.error("failed to get current IP");
    }

    timer = new HashedWheelTimer(10, TimeUnit.MILLISECONDS); // FIXME this is premature and may leak timer
}
 
Example #25
Source File: IdleStateChecker.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
public IdleStateChecker(
        HashedWheelTimer timer,
        int readerIdleTimeSeconds,
        int writerIdleTimeSeconds,
        int allIdleTimeSeconds) {

    this(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds, TimeUnit.SECONDS);
}
 
Example #26
Source File: ModbusTcpSlaveConfig.java    From modbus with Apache License 2.0 5 votes vote down vote up
public ModbusTcpSlaveConfig(Optional<String> instanceId,
                            ExecutorService executor,
                            EventLoopGroup eventLoop,
                            HashedWheelTimer wheelTimer,
                            Consumer<ServerBootstrap> bootstrapConsumer) {

    this.instanceId = instanceId;
    this.executor = executor;
    this.eventLoop = eventLoop;
    this.wheelTimer = wheelTimer;
    this.bootstrapConsumer = bootstrapConsumer;
}
 
Example #27
Source File: DefaultSessionManager.java    From async-gamequery-lib with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public DefaultSessionManager(AbstractSessionIdFactory factory) {
    sessionTimer = new HashedWheelTimer(new ThreadFactoryBuilder().setNameFormat("timeout-%d").setDaemon(true).build());
    directory = new HashMap<>();
    this.factory = (factory != null) ? factory : new DefaultSessionIdFactory();
    this.factory.setLookup(directory);
}
 
Example #28
Source File: ZkIsolatedBookieEnsemblePlacementPolicyTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
    timer = new HashedWheelTimer();
    localZkS = new ZookeeperServerTest(0);
    localZkS.start();

    localZkc = ZooKeeperClient.newBuilder().connectString("127.0.0.1" + ":" + localZkS.getZookeeperPort()).build();
    writableBookies.add(new BookieSocketAddress(BOOKIE1));
    writableBookies.add(new BookieSocketAddress(BOOKIE2));
    writableBookies.add(new BookieSocketAddress(BOOKIE3));
    writableBookies.add(new BookieSocketAddress(BOOKIE4));
    isolationGroups.add("group1");
}
 
Example #29
Source File: PreferLocalBookiePlacementPolicy.java    From herddb with Apache License 2.0 5 votes vote down vote up
@Override
public EnsemblePlacementPolicy initialize(
        ClientConfiguration conf,
        Optional<DNSToSwitchMapping> optionalDnsResolver,
        HashedWheelTimer hashedWheelTimer,
        FeatureProvider featureProvider, StatsLogger statsLogger
) {
    return this;
}
 
Example #30
Source File: BKNamespaceDriver.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private void initializeBookKeeperClients() throws IOException {
    this.eventLoopGroup = getDefaultEventLoopGroup(conf.getBKClientNumberIOThreads());
    this.requestTimer = new HashedWheelTimer(
            new ThreadFactoryBuilder().setNameFormat("DLFactoryTimer-%d").build(),
            conf.getTimeoutTimerTickDurationMs(), TimeUnit.MILLISECONDS,
            conf.getTimeoutTimerNumTicks());
    // Build bookkeeper client for writers
    this.sharedWriterBKCBuilder = createBKCBuilder(
            String.format("bk:%s:factory_writer_shared", namespace),
            conf,
            bkdlConfig.getBkZkServersForWriter(),
            bkdlConfig.getBkLedgersPath(),
            eventLoopGroup,
            requestTimer,
            Optional.of(featureProvider.scope("bkc")),
            statsLogger);
    this.writerBKC = this.sharedWriterBKCBuilder.build();

    // Build bookkeeper client for readers
    if (bkdlConfig.getBkZkServersForWriter().equals(bkdlConfig.getBkZkServersForReader())) {
        this.sharedReaderBKCBuilder = this.sharedWriterBKCBuilder;
    } else {
        this.sharedReaderBKCBuilder = createBKCBuilder(
                String.format("bk:%s:factory_reader_shared", namespace),
                conf,
                bkdlConfig.getBkZkServersForReader(),
                bkdlConfig.getBkLedgersPath(),
                eventLoopGroup,
                requestTimer,
                Optional.<FeatureProvider>absent(),
                statsLogger);
    }
    this.readerBKC = this.sharedReaderBKCBuilder.build();
}