Java Code Examples for java.util.concurrent.Executors#newSingleThreadScheduledExecutor()

The following examples show how to use java.util.concurrent.Executors#newSingleThreadScheduledExecutor() . These examples are extracted from open source projects. 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 Project: RDFS   File: OfferService.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
  if (!shouldRun()) 
    return;
  KeepAliveHeartbeater keepAliveTask = 
      new KeepAliveHeartbeater(namenode, nsRegistration, this.servicePair);
  keepAliveSender = Executors.newSingleThreadScheduledExecutor();
  keepAliveRun = keepAliveSender.scheduleAtFixedRate(keepAliveTask, 0,
                                                     anode.heartBeatInterval,
                                                     TimeUnit.MILLISECONDS);
  while (shouldRun()) {
    try {
      if (isPrimaryService()) {
        servicePair.setPrimaryOfferService(this);
      }
      offerService();
    } catch (Exception e) {
      LOG.error("OfferService encountered exception", e);
    }
  }
  stop();
}
 
Example 2
Source Project: armeria   File: ServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void notGracefulShutdownBlockingTaskExecutor() {
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    final Server server = Server.builder()
                                .blockingTaskExecutor(executor, false)
                                .service("/", (ctx, req) -> HttpResponse.of(200))
                                .build();

    server.start().join();

    executor.execute(() -> {
        try {
            Thread.sleep(processDelayMillis * 2);
        } catch (InterruptedException ignored) {
            // Ignored
        }
    });

    server.stop().join();

    assertThat(server.config().blockingTaskExecutor().isShutdown()).isFalse();
    assertThat(server.config().blockingTaskExecutor().isTerminated()).isFalse();
    assertThat(MoreExecutors.shutdownAndAwaitTermination(executor, 10, TimeUnit.SECONDS)).isTrue();
}
 
Example 3
Source Project: Strata   File: GuavateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_poll_exception() {
  AtomicInteger counter = new AtomicInteger();
  Supplier<String> pollingFn = () -> {
    switch (counter.incrementAndGet()) {
      case 1:
        return null;
      case 2:
        throw new IllegalStateException("Expected");
      default:
        throw new AssertionError("Test failed");
    }
  };

  ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  try {
    CompletableFuture<String> future =
        Guavate.poll(executor, Duration.ofMillis(100), Duration.ofMillis(100), pollingFn);
    assertThatExceptionOfType(CompletionException.class)
        .isThrownBy(() -> future.join())
        .withMessage("java.lang.IllegalStateException: Expected");
  } finally {
    executor.shutdown();
  }
}
 
Example 4
private void scheduleClockUpdating() {
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable, "System Clock");
            thread.setDaemon(true);
            return thread;
        }
    });
    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            now.set(System.currentTimeMillis());
        }
    }, precision, precision, TimeUnit.MILLISECONDS);
}
 
Example 5
Source Project: qpid-jms   File: DiscoveryProvider.java    License: Apache License 2.0 5 votes vote down vote up
private ScheduledExecutorService getSharedScheduler() {
    if (sharedScheduler == null) {
        sharedScheduler = Executors.newSingleThreadScheduledExecutor(
            new QpidJMSThreadFactory("DiscoveryProvider :[" + getDiscoveryURI() + "]", true));
    }

    return sharedScheduler;
}
 
Example 6
Source Project: kcp-netty   File: TcpRttClientHandler.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a client-side handler.
 */
public TcpRttClientHandler(int count) {
    data = Unpooled.buffer(TcpRttClient.SIZE);
    for (int i = 0; i < data.capacity(); i++) {
        data.writeByte((byte) i);
    }

    rtts = new int[count];
    for (int i = 0; i < rtts.length; i++) {
        rtts[i] = -1;
    }
    startTime = System.currentTimeMillis();
    scheduleSrv = Executors.newSingleThreadScheduledExecutor();
}
 
Example 7
/**
 * Creates a new instance, which immediately schedules a synchronization with the marketplace content.
 */
public MarketplaceProxy() {
    try {
        url = new URL(MP_URL);
        this.executorService = Executors.newSingleThreadScheduledExecutor();
        this.refreshJob = this.executorService.scheduleWithFixedDelay(() -> refresh(), 0, refresh_interval,
                TimeUnit.SECONDS);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Something is very wrong - cannot instantiate URL " + MP_URL);
    }
}
 
Example 8
Source Project: emodb   File: ScanUploader.java    License: Apache License 2.0 5 votes vote down vote up
@Inject
public ScanUploader(DataTools dataTools, ScanWorkflow scanWorkflow, ScanStatusDAO scanStatusDAO,
                    StashStateListener stashStateListener, @DelegateCompactionControl CompactionControlSource compactionControlSource, DataCenters dataCenters) {
    _dataTools = checkNotNull(dataTools, "dataTools");
    _scanWorkflow = checkNotNull(scanWorkflow, "scanWorkflow");
    _scanStatusDAO = checkNotNull(scanStatusDAO, "scanStatusDAO");
    _stashStateListener = checkNotNull(stashStateListener, "stashStateListener");
    _compactionControlSource = checkNotNull(compactionControlSource, "compactionControlSource");
    _dataCenters = checkNotNull(dataCenters, "dataCenters");
    _executorService = Executors.newSingleThreadScheduledExecutor();
}
 
Example 9
/**
 * Reads data sources configs and instantiates the constructors for auto load of all data sources, if availble
 * @param config
 */
public AutoOnboardService(ThirdEyeAnomalyConfiguration config) {
  this.runFrequency = config.getAutoOnboardConfiguration().getRunFrequency();
  scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

  Map<String, List<AutoOnboard>> dataSourceToOnboardMap = AutoOnboardUtility.getDataSourceToAutoOnboardMap(
      config.getDataSourcesAsUrl());
  for (List<AutoOnboard> autoOnboards : dataSourceToOnboardMap.values()) {
    autoOnboardServices.addAll(autoOnboards);
  }
}
 
Example 10
Source Project: mpush   File: GatewayServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init() {
    super.init();
    messageDispatcher.register(Command.GATEWAY_PUSH, () -> new GatewayPushHandler(mPushServer.getPushCenter()));

    if (CC.mp.net.traffic_shaping.gateway_server.enabled) {//启用流量整形,限流
        trafficShapingExecutor = Executors.newSingleThreadScheduledExecutor(new NamedPoolThreadFactory(T_TRAFFIC_SHAPING));
        trafficShapingHandler = new GlobalChannelTrafficShapingHandler(
                trafficShapingExecutor,
                write_global_limit, read_global_limit,
                write_channel_limit, read_channel_limit,
                check_interval);
    }
}
 
Example 11
public static ScheduledExecutorService buildSingleThreadScheduledExecutorService(String name) {
    final ThreadFactory threadFactory = ExecutorUtils.getNamedThreadFactory(name);
    final ScheduledExecutorService executor =
            Executors.newSingleThreadScheduledExecutor(threadFactory);
    ExecutorUtils.addDelayedShutdownHook(name, executor);
    return executor;
}
 
Example 12
@Override
public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) {
    this.callbacks = callbacks;

    callbacks.setExtensionName(extensionName);


    dataCollectorGui = new DataCollectorGui(BurpExtender.this);
    callbacks.addSuiteTab(BurpExtender.this);
    callbacks.registerExtensionStateListener(BurpExtender.this);

    loadConfig();

    if (DatabaseUtil.getInstance().initConnection(callbacks, dataCollectorGui.getMysqlHost(), dataCollectorGui.getMysqlPort(),
            dataCollectorGui.getMysqlUser(), dataCollectorGui.getMysqlPassword())) {
        callbacks.printOutput("database connect success");
    } else {
        callbacks.printOutput("database connect fail! please check you mysql config !");
    }

    service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            BurpExtender.this.saveData();
            callbacks.printOutput("Scheduled export execution completed");
        }
    }, 0, 10, TimeUnit.MINUTES);

    callbacks.printOutput("load " + extensionName + " success !");
}
 
Example 13
public ShiftableRateLimiter(double initialRate,
                            double maxRate,
                            double changeRate,
                            long changeInterval,
                            TimeUnit changeIntervalUnit) {
    this.initialRate = initialRate;
    this.maxRate = maxRate;
    this.changeRate = changeRate;
    this.nextRate = initialRate;
    this.changeInterval = changeInterval;
    this.changeIntervalUnit = changeIntervalUnit;
    this.rateLimiter = RateLimiter.create(initialRate);
    this.executor = Executors.newSingleThreadScheduledExecutor();
    this.executor.scheduleAtFixedRate(this, changeInterval, changeInterval, changeIntervalUnit);
}
 
Example 14
@Modified
protected synchronized void modified(Map<String, Object> properties) {
    if (properties != null) {
        String enabled = (String) properties.get("enabled");
        if ("false".equalsIgnoreCase(enabled)) {
            this.enabled = false;
        } else {
            this.enabled = true;
        }
    }

    if (enabled) {
        addRegistryChangeListeners();

        boolean initialDelay = properties == null
                || !"false".equalsIgnoreCase((String) properties.get("initialDelay"));
        if (initialDelay) {
            executor = Executors.newSingleThreadScheduledExecutor();
            delayedInitialize();
        } else {
            initialize();
        }
    } else {
        logger.debug("Disabling channel item provider.");
        disableChannelItemProvider();
    }
}
 
Example 15
Source Project: qmq   File: SyncLagChecker.java    License: Apache License 2.0 4 votes vote down vote up
public SyncLagChecker(final DynamicConfig config, final MasterSyncNettyServer masterSyncNettyServer, final BrokerRegisterService brokerRegisterService) {
    this.config = config;
    this.masterSyncNettyServer = masterSyncNettyServer;
    this.brokerRegisterService = brokerRegisterService;
    this.executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("sync-lag-checker"));
}
 
Example 16
Source Project: Dainty   File: LoadingDialog.java    License: Apache License 2.0 4 votes vote down vote up
public LoadingDialog(@NonNull Context context,@Nullable String title){
    super(context,R.style.LoadingDialog);
    this.title=title;
    setCancelable(false);
    scheduledExecutorService= Executors.newSingleThreadScheduledExecutor();
}
 
Example 17
Source Project: bazel   File: BuildEventServiceModule.java    License: Apache License 2.0 4 votes vote down vote up
private void waitForBuildEventTransportsToClose(
    Map<BuildEventTransport, ListenableFuture<Void>> transportFutures,
    boolean besUploadModeIsSynchronous)
    throws AbruptExitException {
  final ScheduledExecutorService executor =
      Executors.newSingleThreadScheduledExecutor(
          new ThreadFactoryBuilder().setNameFormat("bes-notify-ui-%d").build());
  ScheduledFuture<?> waitMessageFuture = null;

  try {
    // Notify the UI handler when a transport finished closing.
    transportFutures.forEach(
        (bepTransport, closeFuture) ->
            closeFuture.addListener(
                () -> {
                  reporter.post(new BuildEventTransportClosedEvent(bepTransport));
                },
                executor));

    try (AutoProfiler p = GoogleAutoProfilerUtils.logged("waiting for BES close")) {
      Uninterruptibles.getUninterruptibly(Futures.allAsList(transportFutures.values()));
    }
  } catch (ExecutionException e) {
    // Futures.withTimeout wraps the TimeoutException in an ExecutionException when the future
    // times out.
    if (isTimeoutException(e)) {
      throw createAbruptExitException(
          e,
          "The Build Event Protocol upload timed out.",
          ExitCode.TRANSIENT_BUILD_EVENT_SERVICE_UPLOAD_ERROR,
          BuildProgress.Code.BES_UPLOAD_TIMEOUT_ERROR);
    }

    Throwables.throwIfInstanceOf(e.getCause(), AbruptExitException.class);
    throw new RuntimeException(
        String.format(
            "Unexpected Exception '%s' when closing BEP transports, this is a bug.",
            e.getCause().getMessage()));
  } finally {
    if (besUploadModeIsSynchronous) {
      cancelAndResetPendingUploads();
    }
    if (waitMessageFuture != null) {
      waitMessageFuture.cancel(/* mayInterruptIfRunning= */ true);
    }
    executor.shutdown();
  }
}
 
Example 18
Source Project: grpc-proxy   File: StatsTracerFactory.java    License: Apache License 2.0 4 votes vote down vote up
public void start() {
  executor = Executors.newSingleThreadScheduledExecutor();
  executor.scheduleAtFixedRate(this::report, 1, 1, TimeUnit.SECONDS);
}
 
Example 19
public HashBasedPrimaryElectionService(ClusterMembershipService clusterMembershipService, PartitionGroupMembershipService groupMembershipService, ClusterCommunicationService messagingService) {
  this.clusterMembershipService = clusterMembershipService;
  this.groupMembershipService = groupMembershipService;
  this.messagingService = messagingService;
  this.executor = Executors.newSingleThreadScheduledExecutor(Threads.namedThreads("primary-election-%d", log));
}
 
Example 20
Source Project: curator   File: PersistentTtlNode.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * @param client the client
 * @param path path for the parent ZNode
 * @param ttlMs max ttl for the node in milliseconds
 * @param initData data for the node
 */
public PersistentTtlNode(CuratorFramework client, String path, long ttlMs, byte[] initData)
{
    this(client, Executors.newSingleThreadScheduledExecutor(ThreadUtils.newThreadFactory("PersistentTtlNode")), path, ttlMs, initData, DEFAULT_CHILD_NODE_NAME, DEFAULT_TOUCH_SCHEDULE_FACTOR);
}