io.netty.util.Timer Java Examples

The following examples show how to use io.netty.util.Timer. 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: ConsumerImplTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() {
    consumerConf = new ConsumerConfigurationData<>();
    ClientConfigurationData clientConf = new ClientConfigurationData();
    PulsarClientImpl client = mock(PulsarClientImpl.class);
    CompletableFuture<ClientCnx> clientCnxFuture = new CompletableFuture<>();
    CompletableFuture<Consumer<ConsumerImpl>> subscribeFuture = new CompletableFuture<>();
    String topic = "non-persistent://tenant/ns1/my-topic";

    // Mock connection for grabCnx()
    when(client.getConnection(anyString())).thenReturn(clientCnxFuture);
    clientConf.setOperationTimeoutMs(100);
    clientConf.setStatsIntervalSeconds(0);
    when(client.getConfiguration()).thenReturn(clientConf);
    when(client.timer()).thenReturn(mock(Timer.class));

    consumerConf.setSubscriptionName("test-sub");
    consumer = ConsumerImpl.newConsumerImpl(client, topic, consumerConf,
            executorService, -1, false, subscribeFuture, null, null, null,
            true);
}
 
Example #2
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 #3
Source File: InMemoryDeliveryTrackerTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * Adding a message that is about to expire within the tick time should lead
 * to a rejection from the tracker.
 */
@Test
public void testAddWithinTickTime() throws Exception {
    PersistentDispatcherMultipleConsumers dispatcher = mock(PersistentDispatcherMultipleConsumers.class);

    Timer timer = mock(Timer.class);

    AtomicLong clockTime = new AtomicLong();
    Clock clock = mock(Clock.class);
    when(clock.millis()).then(x -> clockTime.get());

    @Cleanup
    InMemoryDelayedDeliveryTracker tracker = new InMemoryDelayedDeliveryTracker(dispatcher, timer, 100, clock);

    clockTime.set(0);

    assertFalse(tracker.addMessage(1, 1, 10));
    assertFalse(tracker.addMessage(2, 2, 99));
    assertTrue(tracker.addMessage(3, 3, 100));
    assertTrue(tracker.addMessage(4, 4, 200));

    assertEquals(tracker.getNumberOfDelayedMessages(), 2);
}
 
Example #4
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 #5
Source File: Server.java    From simulacron with Apache License 2.0 6 votes vote down vote up
private Server(
    AddressResolver addressResolver,
    EventLoopGroup eventLoopGroup,
    Class<? extends ServerChannel> channelClass,
    boolean customEventLoop,
    Timer timer,
    boolean customTimer,
    long bindTimeoutInNanos,
    StubStore stubStore,
    boolean activityLogging) {
  this(
      addressResolver,
      eventLoopGroup,
      customEventLoop,
      timer,
      customTimer,
      bindTimeoutInNanos,
      stubStore,
      activityLogging,
      new ServerBootstrap()
          .group(eventLoopGroup)
          .channel(channelClass)
          .childHandler(new Initializer()));
}
 
Example #6
Source File: Server.java    From simulacron with Apache License 2.0 6 votes vote down vote up
Server(
    AddressResolver addressResolver,
    EventLoopGroup eventLoopGroup,
    boolean customEventLoop,
    Timer timer,
    boolean customTimer,
    long bindTimeoutInNanos,
    StubStore stubStore,
    boolean activityLogging,
    ServerBootstrap serverBootstrap) {
  // custom constructor onyl made to help facilitate testing with a custom bootstrap.
  this.addressResolver = addressResolver;
  this.timer = timer;
  this.customTimer = customTimer;
  this.eventLoopGroup = eventLoopGroup;
  this.customEventLoop = customEventLoop;
  this.serverBootstrap = serverBootstrap;
  this.bindTimeoutInNanos = bindTimeoutInNanos;
  this.stubStore = stubStore;
  this.activityLogging = activityLogging;
}
 
Example #7
Source File: BoundNode.java    From simulacron with Apache License 2.0 5 votes vote down vote up
BoundNode(
    SocketAddress address,
    NodeSpec delegate,
    Map<String, Object> peerInfo,
    BoundCluster cluster,
    BoundDataCenter parent,
    Server server,
    Timer timer,
    Channel channel,
    boolean activityLogging) {
  super(
      address,
      delegate.getName(),
      delegate.getId() != null ? delegate.getId() : 0,
      delegate.getHostId() != null ? delegate.getHostId() : UUID.randomUUID(),
      delegate.getCassandraVersion(),
      delegate.getDSEVersion(),
      peerInfo,
      parent);
  this.cluster = cluster;
  this.server = server;
  // for test purposes server may be null.
  this.bootstrap = server != null ? server.serverBootstrap : null;
  this.timer = timer;
  this.channel = new AtomicReference<>(channel);
  this.stubStore = new StubStore();
  this.activityLogging = activityLogging;
  this.frameCodec = buildFrameCodec(delegate).orElse(parent.getFrameCodec());
}
 
Example #8
Source File: PartitionedProducerImplTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@BeforeTest
public void setup() {
    client = mock(PulsarClientImpl.class);
    schema = mock(Schema.class);
    producerInterceptors = mock(ProducerInterceptors.class);
    producerCreatedFuture = mock(CompletableFuture.class);
    ClientConfigurationData clientConfigurationData = mock(ClientConfigurationData.class);
    Timer timer = mock(Timer.class);

    producerBuilderImpl = new ProducerBuilderImpl(client, Schema.BYTES);

    when(client.getConfiguration()).thenReturn(clientConfigurationData);
    when(client.timer()).thenReturn(timer);
    when(client.newProducer()).thenReturn(producerBuilderImpl);
}
 
Example #9
Source File: UnAckedMessageTrackerTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddAndRemove() throws Exception {
    PulsarClientImpl client = mock(PulsarClientImpl.class);
    Timer timer = new HashedWheelTimer(new DefaultThreadFactory("pulsar-timer", Thread.currentThread().isDaemon()),
            1, TimeUnit.MILLISECONDS);
    when(client.timer()).thenReturn(timer);

    ConsumerBase<byte[]> consumer = mock(ConsumerBase.class);
    doNothing().when(consumer).onAckTimeoutSend(any());
    doNothing().when(consumer).redeliverUnacknowledgedMessages(any());

    UnAckedMessageTracker tracker = new UnAckedMessageTracker(client, consumer, 1000000, 100000);
    tracker.close();

    assertTrue(tracker.isEmpty());
    assertEquals(tracker.size(), 0);

    MessageIdImpl mid = new MessageIdImpl(1L, 1L, -1);
    assertTrue(tracker.add(mid));
    assertFalse(tracker.add(mid));
    assertEquals(tracker.size(), 1);

    ConcurrentOpenHashSet<MessageId> headPartition = tracker.timePartitions.removeFirst();
    headPartition.clear();
    tracker.timePartitions.addLast(headPartition);

    assertFalse(tracker.add(mid));
    assertEquals(tracker.size(), 1);

    assertTrue(tracker.remove(mid));
    assertTrue(tracker.isEmpty());
    assertEquals(tracker.size(), 0);

    timer.stop();
}
 
Example #10
Source File: RetryingProtocolConnection.java    From ffwd with Apache License 2.0 5 votes vote down vote up
public RetryingProtocolConnection(
    AsyncFramework async, Timer timer, Logger log, RetryPolicy policy,
    ProtocolChannelSetup action
) {
    this.async = async;
    this.timer = timer;
    this.log = log;
    this.policy = policy;
    this.action = action;

    this.initialFuture = async.<ProtocolConnection>future();

    trySetup(0);
}
 
Example #11
Source File: ServerTest.java    From simulacron with Apache License 2.0 5 votes vote down vote up
@Test
public void testTryWithResourcesShouldCloseAllClustersButNotEventLoopAndTimerIfProvided()
    throws Exception {
  EventLoopGroup eventLoop = new DefaultEventLoopGroup();
  Timer timer = new HashedWheelTimer();
  BoundCluster cluster;
  MockClient client;

  try (Server server =
      Server.builder()
          .withAddressResolver(localAddressResolver)
          .withTimer(timer)
          .withEventLoopGroup(eventLoop, LocalServerChannel.class)
          .build()) {

    cluster = server.register(ClusterSpec.builder().withNodes(5));
    BoundNode node = cluster.node(0);
    SocketAddress address = node.getAddress();
    client = new MockClient(eventLoop);
    client.connect(address);
  }

  // event loop should not have been closed.
  assertThat(eventLoop.isShutdown()).isFalse();
  // timer should not have since a custom one was not provided.
  cluster
      .getServer()
      .timer
      .newTimeout(
          timeout -> {
            // noop
          },
          1,
          TimeUnit.SECONDS);

  eventLoop.shutdownGracefully(0, 0, TimeUnit.SECONDS);
  timer.stop();
}
 
Example #12
Source File: ServerTest.java    From simulacron with Apache License 2.0 5 votes vote down vote up
@Test
public void testTryWithResourcesShouldCloseAllResources() throws Exception {
  EventLoopGroup eventLoop;
  Timer timer;

  try (Server server = Server.builder().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;
    timer = server.timer;
  }

  // event loop should have been closed since a custom one was not provided.
  assertThat(eventLoop.isShutdown()).isTrue();
  // timer should have since a custom one was not provided.
  try {
    timer.newTimeout(
        timeout -> {
          // noop
        },
        1,
        TimeUnit.SECONDS);
    fail("Expected IllegalStateException");
  } catch (IllegalStateException ise) {
    // expected
  }
}
 
Example #13
Source File: PCCTunnelManagerImpl.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
public PCCTunnelManagerImpl(final int lspsCount, final InetAddress address, final int redelegationTimeout,
                            final int stateTimeout, final Timer timer, final Optional<TimerHandler> timerHandler) {
    Preconditions.checkArgument(lspsCount >= 0);
    this.redelegationTimeout = redelegationTimeout;
    this.stateTimeout = stateTimeout;
    this.plspIDsCounter = new AtomicLong(lspsCount);
    this.address = InetAddresses.toAddrString(requireNonNull(address));
    this.timer = requireNonNull(timer);
    this.timerHandler = timerHandler;
    this.lspsCount = lspsCount;
}
 
Example #14
Source File: ShutDownManager.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
public static void shutdownGlobalThreadPools() {
    log.info("invoke shutdownGlobalThreadPools");
    ThreadPool serverWorkThreadPool = ServerWorkThreadPoolInstance.getInstance();

    EpollEventLoopGroup epollBossGroup = ServerAcceptorThreadPoolInstance.getEpollInstance();
    NioEventLoopGroup nioBossGroup = ServerAcceptorThreadPoolInstance.getNioInstance();
    EpollEventLoopGroup epollWorkerGroup = ServerIoThreadPoolInstance.getEpollInstance();
    NioEventLoopGroup nioWorkerGroup = ServerIoThreadPoolInstance.getNioInstance();
    Timer clientHealthCheckerTimer = ClientHealthCheckTimerInstance.getInstance();
    Timer clientTimeOutTimer = TimerInstance.getInstance();

    if (epollBossGroup != null) {
        epollBossGroup.shutdownGracefully();
    }
    if (nioBossGroup != null) {
        nioBossGroup.shutdownGracefully();
    }
    if (epollWorkerGroup != null) {
        epollWorkerGroup.shutdownGracefully();
    }
    if (nioWorkerGroup != null) {
        nioWorkerGroup.shutdownGracefully();
    }
    if (serverWorkThreadPool != null) {
        serverWorkThreadPool.stop();
    }
    BrpcThreadPoolManager.getInstance().stopAll();
    BootstrapManager bootstrapManager = BootstrapManager.getInstance();
    bootstrapManager.removeAll();
    if (clientHealthCheckerTimer != null) {
        clientHealthCheckerTimer.stop();
    }
    if (clientTimeOutTimer != null) {
        clientTimeOutTimer.stop();
    }
}
 
Example #15
Source File: InstructionSchedulerFactoryImpl.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
public InstructionSchedulerFactoryImpl(
        final DataBroker dataProvider,
        final RpcProviderService rpcProviderRegistry,
        final NotificationPublishService notifs,
        final Timer timer,
        final ClusterSingletonServiceProvider cssp,
        final BundleContext bundleContext) {
    this.dataProvider = requireNonNull(dataProvider);
    this.notifs = requireNonNull(notifs);
    this.timer = requireNonNull(timer);
    this.rpcProviderRegistry = requireNonNull(rpcProviderRegistry);
    this.bundleContext = requireNonNull(bundleContext);
    this.cssp = requireNonNull(cssp);
}
 
Example #16
Source File: ProgrammingServiceImpl.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
ProgrammingServiceImpl(final DataBroker dataProvider, final NotificationPublishService notifs,
        final ListeningExecutorService executor, final RpcProviderService rpcProviderRegistry,
        final ClusterSingletonServiceProvider cssp, final Timer timer, final String instructionId) {
    this.dataProvider = requireNonNull(dataProvider);
    this.instructionId = requireNonNull(instructionId);
    this.notifs = requireNonNull(notifs);
    this.executor = requireNonNull(executor);
    this.rpcProviderRegistry = requireNonNull(rpcProviderRegistry);
    this.timer = requireNonNull(timer);
    this.qid = KeyedInstanceIdentifier.builder(InstructionsQueue.class,
            new InstructionsQueueKey(this.instructionId)).build();
    this.sgi = ServiceGroupIdentifier.create(this.instructionId + "-service-group");
    LOG.info("Creating Programming Service {}.", this.sgi.getName());
    this.csspReg = cssp.registerClusterSingletonService(this);
}
 
Example #17
Source File: MetadataGrpcDataSender.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() {
    if (shutdown) {
        return;
    }
    this.shutdown = true;

    final Timer retryTimer = this.retryTimer;
    if (retryTimer != null) {
        retryTimer.stop();
    }
    super.release();
}
 
Example #18
Source File: MasterSlaveConnectionManager.java    From redisson with Apache License 2.0 4 votes vote down vote up
@Override
public Timer timer() {
    return null;
}
 
Example #19
Source File: RedisClientConfig.java    From redisson with Apache License 2.0 4 votes vote down vote up
public RedisClientConfig setTimer(Timer timer) {
    this.timer = timer;
    return this;
}
 
Example #20
Source File: InMemoryDeliveryTrackerTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {
    PersistentDispatcherMultipleConsumers dispatcher = mock(PersistentDispatcherMultipleConsumers.class);

    Timer timer = mock(Timer.class);

    AtomicLong clockTime = new AtomicLong();
    Clock clock = mock(Clock.class);
    when(clock.millis()).then(x -> clockTime.get());

    @Cleanup
    InMemoryDelayedDeliveryTracker tracker = new InMemoryDelayedDeliveryTracker(dispatcher, timer, 1, clock);

    assertFalse(tracker.hasMessageAvailable());

    assertTrue(tracker.addMessage(2, 2, 20));
    assertTrue(tracker.addMessage(1, 1, 10));
    assertTrue(tracker.addMessage(3, 3, 30));
    assertTrue(tracker.addMessage(5, 5, 50));
    assertTrue(tracker.addMessage(4, 4, 40));

    assertFalse(tracker.hasMessageAvailable());
    assertEquals(tracker.getNumberOfDelayedMessages(), 5);

    assertEquals(tracker.getScheduledMessages(10), Collections.emptySet());

    // Move time forward
    clockTime.set(15);

    // Message is rejected by tracker since it's already ready to send
    assertFalse(tracker.addMessage(6, 6, 10));

    assertEquals(tracker.getNumberOfDelayedMessages(), 5);
    assertTrue(tracker.hasMessageAvailable());
    Set<PositionImpl> scheduled = tracker.getScheduledMessages(10);
    assertEquals(scheduled.size(), 1);

    // Move time forward
    clockTime.set(60);

    assertEquals(tracker.getNumberOfDelayedMessages(), 4);
    assertTrue(tracker.hasMessageAvailable());
    scheduled = tracker.getScheduledMessages(1);
    assertEquals(scheduled.size(), 1);

    assertEquals(tracker.getNumberOfDelayedMessages(), 3);
    assertTrue(tracker.hasMessageAvailable());
    scheduled = tracker.getScheduledMessages(3);
    assertEquals(scheduled.size(), 3);

    assertEquals(tracker.getNumberOfDelayedMessages(), 0);
    assertFalse(tracker.hasMessageAvailable());
    assertEquals(tracker.getScheduledMessages(10), Collections.emptySet());
}
 
Example #21
Source File: XioConfigBuilderBase.java    From xio with Apache License 2.0 4 votes vote down vote up
protected Timer getTimer() {
  return timer;
}
 
Example #22
Source File: XioConfigBuilderBase.java    From xio with Apache License 2.0 4 votes vote down vote up
public T setTimer(Timer timer) {
  this.timer = timer;
  return (T) this;
}
 
Example #23
Source File: RedisClientConfig.java    From redisson with Apache License 2.0 4 votes vote down vote up
public Timer getTimer() {
    return timer;
}
 
Example #24
Source File: ConnectionWatchdog.java    From redisson with Apache License 2.0 4 votes vote down vote up
public ConnectionWatchdog(Bootstrap bootstrap, ChannelGroup channels, Timer timer) {
    this.bootstrap = bootstrap;
    this.channels  = channels;
    this.timer = timer;
}
 
Example #25
Source File: RedisClient.java    From redisson with Apache License 2.0 4 votes vote down vote up
public Timer getTimer() {
    return timer;
}
 
Example #26
Source File: ConnectionWatchdog.java    From Jupiter with Apache License 2.0 4 votes vote down vote up
public ConnectionWatchdog(Bootstrap bootstrap, Timer timer, SocketAddress remoteAddress, JChannelGroup group) {
    this.bootstrap = bootstrap;
    this.timer = timer;
    this.remoteAddress = remoteAddress;
    this.group = group;
}
 
Example #27
Source File: MetadataClientMock.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
private Timer newTimer(String name) {
    ThreadFactory threadFactory = new PinpointThreadFactory(PinpointThreadFactory.DEFAULT_THREAD_NAME_PREFIX + name, true);
    return new HashedWheelTimer(threadFactory, 100, TimeUnit.MILLISECONDS, 512, false, 100);
}
 
Example #28
Source File: MetadataGrpcDataSender.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
private Timer newTimer(String name) {
    ThreadFactory threadFactory = new PinpointThreadFactory(PinpointThreadFactory.DEFAULT_THREAD_NAME_PREFIX + name, true);
    return new HashedWheelTimer(threadFactory, 100, TimeUnit.MILLISECONDS, 512, false, MAX_PENDING_TIMEOUTS);
}
 
Example #29
Source File: PulsarClientImpl.java    From pulsar with Apache License 2.0 4 votes vote down vote up
/** visible for pulsar-functions **/
public Timer timer() {
    return timer;
}
 
Example #30
Source File: NettyService.java    From WeCross with Apache License 2.0 4 votes vote down vote up
public Timer getTimer() {
    return timer;
}