java.util.concurrent.TimeUnit Java Examples

The following examples show how to use java.util.concurrent.TimeUnit. 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: ManageSqlServerKeysWithAzureKeyVaultKey.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {
        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));


        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
            .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
            .withSerializerAdapter(new AzureJacksonAdapter())
            .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
            .withReadTimeout(150, TimeUnit.SECONDS)
            .withLogLevel(LogLevel.BODY)
            .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure, credentials.clientId());
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #2
Source File: BatchWriter.java    From examples with Apache License 2.0 6 votes vote down vote up
public BatchWriter(EmbeddedSolrServer solr, int batchSize, TaskID tid,
    int writerThreads, int queueSize) {
  this.solr = solr;
  this.writerThreads = writerThreads;
  this.queueSize = queueSize;
  taskId = tid;

  // we need to obtain the settings before the constructor
  if (writerThreads != 0) {
    batchPool = new ThreadPoolExecutor(writerThreads, writerThreads, 5,
        TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(queueSize),
        new ThreadPoolExecutor.CallerRunsPolicy());
  } else { // single threaded case
    batchPool = null;
  }
}
 
Example #3
Source File: AutoScanner.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
private void startConfigRetentionScheduler()
{
	scheduler2 = Executors.newSingleThreadScheduledExecutor();//we only need a single thread
	
	retentionTask = new MetricsRetentionTask(this.context,  context.getMyperfConfig().getRecordRententionDays(), null);
	configScanTask = new GlobalVariableChangeScanTask(this.context, this.appUser);
	
	int secOfTheDay = getCurrentSeconds();
	int interval = context.getMyperfConfig().getScannerIntervalSeconds();
	maxScanIdleTime = interval * 3000;
	if(maxScanIdleTime < 300000L) maxScanIdleTime = 300000L;//minimum check time 5 minutes
	logger.info("maximun alowed hange time: "+maxScanIdleTime);
	
	int configDelay = (int)Math.ceil(((double)secOfTheDay)/(720*60))*720*60 - secOfTheDay;
	int configDelay2 = (int)Math.ceil(((double)secOfTheDay)/(1440*60))*1440*60 - secOfTheDay;
	int monitorDelay = (int)Math.ceil(((double)secOfTheDay)/(600))*600 - secOfTheDay; //monitor delay
	ScheduledFuture<?> runtimeTaskFuture2 = scheduler2.scheduleAtFixedRate(retentionTask, 
			configDelay2+60, 24*3600, TimeUnit.SECONDS);//once a day
	ScheduledFuture<?> runtimeTaskFuture3 = scheduler2.scheduleAtFixedRate(configScanTask, 
			configDelay+120, 12*3600, TimeUnit.SECONDS);//twice a day
	logger.info("Rentention Task and configuratiion scan task scheduled.");
	
	
}
 
Example #4
Source File: SimpleLifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
void consistentThreadDeliveringWhenHasElements() throws InterruptedException {
    Scheduler deliveryScheduler = Schedulers.newSingle("delivery");
    AtomicReference<String> threadName = new AtomicReference<>();
    Scheduler acquireScheduler = Schedulers.newSingle("acquire");
    PoolConfig<PoolableTest> testConfig = poolableTestConfig(1, 1,
            Mono.fromCallable(PoolableTest::new)
                .subscribeOn(Schedulers.newParallel("poolable test allocator")),
            deliveryScheduler);
    SimpleLifoPool<PoolableTest> pool = new SimpleLifoPool<>(testConfig);

    //the pool is started with one available element
    //we prepare to acquire it
    Mono<PooledRef<PoolableTest>> borrower = pool.acquire();
    CountDownLatch latch = new CountDownLatch(1);

    //we actually request the acquire from a separate thread and see from which thread the element was delivered
    acquireScheduler.schedule(() -> borrower.subscribe(v -> threadName.set(Thread.currentThread().getName()), e -> latch.countDown(), latch::countDown));
    latch.await(1, TimeUnit.SECONDS);

    assertThat(threadName.get())
            .startsWith("delivery-");
}
 
Example #5
Source File: ScanUploadSchedulingService.java    From emodb with Apache License 2.0 6 votes vote down vote up
/**
 * Schedule a daily scan and upload to run once daily.
 */
private void scheduleScan(final ScheduledDailyScanUpload scanUpload) {
    // Schedule the first iteration for this scan

    Instant now = _clock.instant();
    final Instant nextExecTime = scanUpload.getNextExecutionTimeAfter(now);
    scheduleNextScanExecution(scanUpload, now, nextExecTime);

    // Schedule the pending scan count to increment 45 minutes before the scan begins.

    Instant pendingExecTime = nextExecTime.minus(SCAN_PENDING_PERIOD);
    if (pendingExecTime.isBefore(now)) {
        // We're already within the pending exec time.  Mark that the scan is pending and schedule the
        // first iteration for the next day.
        maybeAddPendingScan(scanUpload, nextExecTime);
        pendingExecTime = pendingExecTime.plus(Duration.ofDays(1));
    }

    _service.scheduleAtFixedRate(
            () -> maybeAddPendingScan(scanUpload, scanUpload.getNextExecutionTimeAfter(_clock.instant())),
            Duration.between(now, pendingExecTime).toMillis(),
            Duration.ofDays(1).toMillis(),
            TimeUnit.MILLISECONDS);
}
 
Example #6
Source File: AmqpReceiver.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void stopOnSchedule(long timeout, final AsyncResult request) {
   LOG.trace("Receiver {} scheduling stop", this);
   // We need to drain the credit if no message(s) arrive to use it.
   final ScheduledFuture<?> future = getSession().getScheduler().schedule(new Runnable() {
      @Override
      public void run() {
         LOG.trace("Receiver {} running scheduled stop", this);
         if (getEndpoint().getRemoteCredit() != 0) {
            stop(request);
            session.pumpToProtonTransport(request);
         }
      }
   }, timeout, TimeUnit.MILLISECONDS);

   stopRequest = new ScheduledRequest(future, request);
}
 
Example #7
Source File: ScheduledExecutorTimeoutWatcher.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
@Override
public TimeoutWatch schedule(TimeoutExecution execution) {
    ScheduledFuture<?> future = executor.schedule(execution::timeoutAndInterrupt, execution.timeoutInMillis(),
            TimeUnit.MILLISECONDS);
    return new TimeoutWatch() {
        @Override
        public boolean isRunning() {
            return !future.isDone();
        }

        @Override
        public void cancel() {
            future.cancel(true);
        }
    };
}
 
Example #8
Source File: VFSTransportTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "Sending a file through VFS Transport : "
        + "transport.vfs.FileURI = /home/someuser/somedir " + "transport.vfs.ContentType = text/plain, "
        + "transport.vfs.FileNamePattern = - *\\.txt, " + "transport.PollInterval=1,"
        + " transport.vfs.ReplyFileName = out.txt ")
public void testVFSProxyReplyFileName_Normal() throws Exception {

    //Related proxy : VFSProxy9
    File sourceFile = new File(pathToVfsDir + File.separator + "test.txt");
    File targetFile = new File(proxyVFSRoots.get("VFSProxy9") + File.separator + "in" + File.separator + "test.txt");
    File outfile = new File(proxyVFSRoots.get("VFSProxy9") + File.separator + "out" + File.separator + "out.txt");

    FileUtils.copyFile(sourceFile, targetFile);

    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
            .until(isFileExist(outfile));
    Assert.assertTrue(outfile.exists());
    Assert.assertTrue(doesFileContain(outfile, "[email protected]"));
}
 
Example #9
Source File: KafkaNotificationProvider.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void stop() {
    if (consumers != null && consumers.size() > 0) {
        for (final PeriodicNotificationConsumer consumer : consumers) {
            consumer.shutdown();
        }
    }
    if (executor != null) {
        executor.shutdown();
    }
    running = false;
    try {
        if (!executor.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
            LOG.info("Timed out waiting for consumer threads to shut down, exiting uncleanly");
            executor.shutdownNow();
        }
    } catch (final InterruptedException e) {
        LOG.info("Interrupted during shutdown, exiting uncleanly");
    }
}
 
Example #10
Source File: DiscordApiBuilderDelegateImpl.java    From Javacord with Apache License 2.0 6 votes vote down vote up
private void setRecommendedTotalShards(CompletableFuture<Void> future) {
    DiscordApiImpl api = new DiscordApiImpl(
            token, globalRatelimiter, proxySelector, proxy, proxyAuthenticator, trustAllCertificates);
    RestRequest<JsonNode> botGatewayRequest = new RestRequest<>(api, RestMethod.GET, RestEndpoint.GATEWAY_BOT);
    botGatewayRequest
            .execute(RestRequestResult::getJsonBody)
            .thenAccept(resultJson -> {
                DiscordWebSocketAdapter.setGateway(resultJson.get("url").asText());
                setTotalShards(resultJson.get("shards").asInt());
                retryAttempt.set(0);
                future.complete(null);
            })
            .exceptionally(t -> {
                int retryDelay = api.getReconnectDelay(retryAttempt.incrementAndGet());
                logger.info("Retrying to get recommended total shards in {} seconds!", retryDelay);
                api.getThreadPool().getScheduler().schedule(
                        () -> setRecommendedTotalShards(future), retryDelay, TimeUnit.SECONDS);
                return null;
            })
            .whenComplete((nothing, throwable) -> api.disconnect());
}
 
Example #11
Source File: SaveScrollNow.java    From Onosendai with Apache License 2.0 6 votes vote down vote up
public boolean awaitScrollStores (final Set<Integer> waitForColumnIds, final int timeout, final TimeUnit unit) {
	final long timeoutNanos = unit.toNanos(timeout);
	final long startTime = now();
	while (true) {
		synchronized (this.storedColumnIds) {
			if (this.storedColumnIds.containsAll(waitForColumnIds)) return true;
		}
		if (now() - startTime > timeoutNanos) return false;
		try {
			Thread.sleep(100);
		}
		catch (InterruptedException e) {
			return false;
		}
	}
}
 
Example #12
Source File: TimelineCallbackImpledFuture.java    From tablestore-timeline with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Entry get(long timeout, TimeUnit unit) throws TimeoutException, InterruptedException, ExecutionException {
    Preconditions.checkNotNull(unit, "Time unit should not be null");
    long endTime = System.currentTimeMillis() + unit.toMillis(timeout);
    synchronized(this) {
        while(!this.completed) {
            long waitTime = endTime - System.currentTimeMillis();
            if (waitTime <= 0L) {
                throw new TimeoutException();
            }

            this.wait(waitTime);
        }

        return this.getResultWithoutLock();
    }
}
 
Example #13
Source File: AbortSlowConsumer1Test.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60 * 1000)
public void testAbortAlreadyClosedConnection() throws Exception {
   Connection conn = createConnectionFactory().createConnection();
   conn.setExceptionListener(this);

   Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   sess.createConsumer(destination);
   conn.start();
   startProducers(destination, 20);
   TimeUnit.SECONDS.sleep(1);
   LOG.info("closing connection: " + conn);
   conn.close();

   TimeUnit.SECONDS.sleep(5);
   assertTrue("no exceptions : " + exceptions, exceptions.isEmpty());
}
 
Example #14
Source File: SingleConcatTest.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
  TestScheduler testScheduler = new TestScheduler();

  final Single<List<Integer>> first = Single.timer(2, TimeUnit.SECONDS, testScheduler)
          .map(u -> Arrays.asList(1, 2, 3));
  final Single<List<Integer>> second = Single.just(Collections.emptyList());
  final Single<List<Integer>> third = Single.just(Collections.singletonList(4));
  final Single<List<Integer>> fourth = Single.just(Collections.singletonList(5));

  Single<List<Integer>> subject = Observable
    .fromIterable(Arrays.asList(first, second, third, fourth))
    .concatMapSingle(single -> single)
    .reduce(new ArrayList<>(), (seed, items) -> {
      seed.addAll(items);
      return seed;
    });

    TestObserver<List<Integer>> testObserver = subject.test();
    testScheduler.advanceTimeBy(3, TimeUnit.SECONDS);

    System.out.println(testObserver.values());
    testObserver.assertValue(list -> list.equals(Arrays.asList(1, 2, 3, 4, 5))); 
    // 5 is currently missing ; fourth was never subscribed in the first place
}
 
Example #15
Source File: VoicePlaceSelectionHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void placeAuthorized(UUID placeId) {
   long startTime = System.nanoTime();
   PlatformMessage msg = PlatformMessage.buildRequest(
      VoiceService.StartPlaceRequest.builder().withAssistant(assistant).build(),
      bridgeAddress,
      Address.platformService(VoiceService.NAMESPACE)
   )
   .withCorrelationId(IrisUUID.randomUUID().toString())
   .withPlaceId(placeId)
   .withPopulation(populationCacheMgr.getPopulationByPlaceId(placeId))
   .withTimeToLive((int) config.getRequestTimeoutMs())
   .create();
   try {
      busClient.request(msg).get(config.getRequestTimeoutMs(), TimeUnit.MILLISECONDS);
      metrics.timeServiceSuccess(msg.getMessageType(), startTime);
   } catch(Exception e) {
      logger.warn("failed to start place {}", placeId, e);
      metrics.timeServiceFailure(msg.getMessageType(), startTime);
   }
}
 
Example #16
Source File: RdfCloudTripleStoreSelectivityEvaluationStatisticsTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException {

    mock = new MockInstance("accumulo");
    PasswordToken pToken = new PasswordToken("pass".getBytes());
    conn = mock.getConnector("user", pToken);

    config = new BatchWriterConfig();
    config.setMaxMemory(1000);
    config.setMaxLatency(1000, TimeUnit.SECONDS);
    config.setMaxWriteThreads(10);

    if (conn.tableOperations().exists("rya_prospects")) {
        conn.tableOperations().delete("rya_prospects");
    }
    if (conn.tableOperations().exists("rya_selectivity")) {
        conn.tableOperations().delete("rya_selectivity");
    }

    arc = new AccumuloRdfConfiguration();
    arc.setTableLayoutStrategy(new TablePrefixLayoutStrategy());
    arc.setMaxRangesForScanner(300);

}
 
Example #17
Source File: TestRunController.java    From etf-webapp with European Union Public License 1.2 6 votes vote down vote up
@PostConstruct
public void init() throws ParseException, ConfigurationException, IOException, StorageException {
    logger.info(Runtime.getRuntime().availableProcessors() + " cores available.");

    // SEL dir
    System.setProperty("ETF_SEL_GROOVY",
            etfConfig.getPropertyAsFile(EtfConstants.ETF_PROJECTS_DIR).expandPath("sui").getPath());
    simplifiedWorkflows = "simplified".equals(etfConfig.getProperty(EtfConfigController.ETF_WORKFLOWS));
    testRunDao = dataStorageService.getDao(TestRunDto.class);

    timer = new Timer(true);
    // Trigger every 30 Minutes
    final TimedExpiredItemsRemover timedExpiredItemsRemover = new TimedExpiredItemsRemover();
    timedExpiredItemsRemover.addExpirationItemHolder(
            (l, timeUnit) -> taskPoolRegistry.removeDone(),
            0, TimeUnit.HOURS);
    // 7,5 minutes
    timer.scheduleAtFixedRate(timedExpiredItemsRemover, 450000, 450000);

    logger.info("Test Run controller initialized!");
}
 
Example #18
Source File: EventInjectorTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Test
public void injectKeyEventUpWithNoDown() throws Exception {
  ActivityScenario<SendActivity> scenario = ActivityScenario.launch(SendActivity.class);

  scenario.onActivity(
      sendActivity -> {
        View view = sendActivity.findViewById(R.id.send_data_edit_text);
        assertTrue(view.requestFocus());
        latch.countDown();
      });

  assertTrue("Timed out!", latch.await(10, TimeUnit.SECONDS));
  KeyCharacterMap keyCharacterMap = UiControllerImpl.getKeyCharacterMap();
  KeyEvent[] events = keyCharacterMap.getEvents("a".toCharArray());
  assertTrue(injector.injectKeyEvent(events[1]));
}
 
Example #19
Source File: BLSBenchmark.java    From teku with Apache License 2.0 6 votes vote down vote up
@Benchmark
@Warmup(iterations = 5, time = 1000, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 1000, timeUnit = TimeUnit.MILLISECONDS)
public void verifySignatureBatchedNonParallelSinglePairing() {
  boolean res =
      BLS.batchVerify(
          keyPairs.stream()
              .map(kp -> Collections.singletonList(kp.getPublicKey()))
              .limit(sigCnt)
              .collect(Collectors.toList()),
          messages.subList(0, sigCnt),
          signatures.subList(0, sigCnt),
          false,
          false);
  if (!res) throw new IllegalStateException();
}
 
Example #20
Source File: FixedWindowRateLimiter.java    From orianna with MIT License 6 votes vote down vote up
@Override
public void restrictFor(final long time, final TimeUnit unit) {
    synchronized(resetterLock) {
        permitter.drainPermits();

        if(drainer != null) {
            drainer.cancel();
            drainer.cancelled = true;
        }

        if(resetter != null) {
            resetter.cancel();
            resetter.cancelled = true;
        }

        resetter = new Resetter();
        timer.schedule(resetter, unit.toMillis(time));
    }
}
 
Example #21
Source File: OkHttpMetricsEventListenerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void timeFailureDueToTimeout(@WiremockResolver.Wiremock WireMockServer server) {
    Request request = new Request.Builder()
            .url(server.baseUrl())
            .build();

    server.stop();

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(1, TimeUnit.MILLISECONDS)
            .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests")
                    .tags(Tags.of("foo", "bar"))
                    .uriMapper(URI_MAPPER)
                    .build())
            .build();

    try {
        client.newCall(request).execute().close();
        fail("Expected IOException.");
    } catch (IOException ignored) {
        // expected
    }

    assertThat(registry.get("okhttp.requests")
            .tags("foo", "bar", "uri", URI_EXAMPLE_VALUE, "status", "IO_ERROR", "target.host", "localhost")
            .timer().count()).isEqualTo(1L);
}
 
Example #22
Source File: TestChangeZoneState.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws ApiSenderException, InterruptedException {
    List<ZoneInventory> zones = api.createZones(1);
    ZoneInventory zone = zones.get(0);
    TimeUnit.SECONDS.sleep(1);
    ZoneInventory s1 = api.changeZoneState(zone.getUuid(), ZoneStateEvent.disable);
    Assert.assertEquals(ZoneState.Disabled.toString(), s1.getState());
    Assert.assertFalse(s1.getCreateDate().equals(s1.getLastOpDate()));
}
 
Example #23
Source File: TestMetaServer.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    cluster = new LogServiceCluster(3);
    cluster.createWorkers(3);
    workers = cluster.getWorkers();
    assert(workers.size() == 3);

    RaftProperties properties = new RaftProperties();
    RaftClientConfigKeys.Rpc.setRequestTimeout(properties, TimeDuration.valueOf(15, TimeUnit.SECONDS));

    cluster.getMasters().parallelStream().forEach(master ->
        ((MetaStateMachine)master.getMetaStateMachine()).setProperties(properties));

    client = new LogServiceClient(cluster.getMetaIdentity(), properties) {
      @Override
      public LogStream createLog(LogName logName) throws IOException {
        createCount.incrementAndGet();
        return super.createLog(logName);
      }

      @Override
      public void deleteLog(LogName logName) throws IOException {
        deleteCount.incrementAndGet();
        super.deleteLog(logName);
      }

      @Override
      public List<LogInfo> listLogs() throws IOException {
        listCount.incrementAndGet();
        return super.listLogs();
      }
    };
}
 
Example #24
Source File: TestLocalStorage6.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws ApiSenderException, InterruptedException {
    ClusterInventory cluster = deployer.clusters.get("Cluster1");
    PrimaryStorageInventory local = deployer.primaryStorages.get("local");
    PrimaryStorageInventory local2 = deployer.primaryStorages.get("local2");


    APIAddKVMHostMsg msg = new APIAddKVMHostMsg();
    msg.setName("host1");
    msg.setClusterUuid(cluster.getUuid());
    msg.setManagementIp("127.0.0.1");
    msg.setSession(api.getAdminSession());
    msg.setUsername("root");
    msg.setPassword("password");
    ApiSender sender = api.getApiSender();
    APIAddHostEvent evt = sender.send(msg, APIAddHostEvent.class);
    HostInventory host1 = evt.getInventory();


    HostVO hvo1 = dbf.findByUuid(host1.getUuid(), HostVO.class);
    hvo1.setStatus(HostStatus.Disconnected);
    dbf.update(hvo1);
    HostGlobalConfig.PING_HOST_INTERVAL.updateValue(1);

    TimeUnit.SECONDS.sleep(5);

    LocalStorageHostRefVO href = new LocalStorageHostRefVOFinder().findByPrimaryKey(host1.getUuid(), local.getUuid());
    PrimaryStorageVO lvo = dbf.findByUuid(local.getUuid(), PrimaryStorageVO.class);
    if (href == null) {
        href = new LocalStorageHostRefVOFinder().findByPrimaryKey(host1.getUuid(), local2.getUuid());
        lvo = dbf.findByUuid(local2.getUuid(), PrimaryStorageVO.class);
    }
    Assert.assertEquals(href.getTotalCapacity(), totalSize);
    Assert.assertEquals(href.getTotalPhysicalCapacity(), totalSize);


    Assert.assertEquals(totalSize, lvo.getCapacity().getTotalCapacity());
    Assert.assertEquals(totalSize, lvo.getCapacity().getTotalPhysicalCapacity());
}
 
Example #25
Source File: PerformanceLevelTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the {@link PerformanceLevel#forDuration(long, TimeUnit)} method.
 */
@Test
public void testForDuration() {
    assertSame(SLOW,        forDuration(500, TimeUnit.MILLISECONDS));
    assertSame(SLOWER,      forDuration(2,   TimeUnit.SECONDS));
    assertSame(SLOWEST,     forDuration(6,   TimeUnit.SECONDS));
    assertSame(PERFORMANCE, forDuration(50,  TimeUnit.MILLISECONDS));
}
 
Example #26
Source File: TransportSQLActionClassLifecycleTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testSysOperationsLog() throws Exception {
    execute("set global transient stats.enabled = false");

    execute(
        "select count(*), race from characters group by race order by count(*) desc limit 2");
    SQLResponse resp = execute("select count(*) from sys.operations_log");
    assertThat((Long) resp.rows()[0][0], is(0L));

    execute("set global transient stats.enabled = true, stats.operations_log_size=10");
    waitNoPendingTasksOnAll();

    execute(
        "select count(*), race from characters group by race order by count(*) desc limit 2");

    assertBusy(() -> {
        SQLResponse response = execute("select * from sys.operations_log order by ended limit 3");

        List<String> names = new ArrayList<>();
        for (Object[] objects : response.rows()) {
            names.add((String) objects[4]);
        }
        assertThat(names, Matchers.anyOf(
            Matchers.hasItems("distributing collect", "distributing collect"),
            Matchers.hasItems("collect", "localMerge"),

            // the select * from sys.operations_log has 2 collect operations (1 per node)
            Matchers.hasItems("collect", "collect"),
            Matchers.hasItems("distributed merge", "localMerge")));
    }, 10L, TimeUnit.SECONDS);

    execute("set global transient stats.enabled = false");
    waitNoPendingTasksOnAll();
    resp = execute("select count(*) from sys.operations_log");
    assertThat((Long) resp.rows()[0][0], is(0L));
}
 
Example #27
Source File: PeriodicLocationTracker.java    From background_location_updates with Apache License 2.0 5 votes vote down vote up
public static boolean scheduleLocationTracking(int requestInterval) {
    OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(PeriodicLocationTracker.class)
            .setInitialDelay(requestInterval, TimeUnit.MILLISECONDS)
            .setInputData(
                    new Data.Builder()
                            .putInt("requestInterval", requestInterval)
                            .build())
            .addTag(TRACK_IDENT)
            .build();
    WorkManager.getInstance().beginUniqueWork(TRACK_IDENT, ExistingWorkPolicy.REPLACE, request).enqueue();
    return true;
}
 
Example #28
Source File: PutManagerTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Submits put blob operations that are expected to succeed, waits for completion, and asserts success.
 * @param shouldCloseRouterAfter whether the router should be closed after the operation.
 */
private void submitPutsAndAssertSuccess(boolean shouldCloseRouterAfter) throws Exception {
  submitPut().await(MAX_WAIT_MS, TimeUnit.MILLISECONDS);
  assertSuccess();
  if (shouldCloseRouterAfter) {
    assertCloseCleanup();
  }
}
 
Example #29
Source File: UtilCache.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> createLineInfo(int keyNum, K key, CacheLine<V> line) {
    Map<String, Object> lineInfo = new HashMap<>();
    lineInfo.put("elementKey", key);

    if (line.getLoadTimeNanos() > 0) {
        lineInfo.put("expireTimeMillis", TimeUnit.MILLISECONDS.convert(line.getExpireTimeNanos() - System.nanoTime(), TimeUnit.NANOSECONDS));
    }
    lineInfo.put("lineSize", findSizeInBytes(line.getValue(), key)); // SCIPIO: pass key
    lineInfo.put("keyNum", keyNum);
    return lineInfo;
}
 
Example #30
Source File: ConsumeKafka_2_0.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnUnscheduled
public void interruptActiveThreads() {
    // There are known issues with the Kafka client library that result in the client code hanging
    // indefinitely when unable to communicate with the broker. In order to address this, we will wait
    // up to 30 seconds for the Threads to finish and then will call Consumer.wakeup() to trigger the
    // thread to wakeup when it is blocked, waiting on a response.
    final long nanosToWait = TimeUnit.SECONDS.toNanos(5L);
    final long start = System.nanoTime();
    while (System.nanoTime() - start < nanosToWait && !activeLeases.isEmpty()) {
        try {
            Thread.sleep(100L);
        } catch (final InterruptedException ie) {
            Thread.currentThread().interrupt();
            return;
        }
    }

    if (!activeLeases.isEmpty()) {
        int count = 0;
        for (final ConsumerLease lease : activeLeases) {
            getLogger().info("Consumer {} has not finished after waiting 30 seconds; will attempt to wake-up the lease", new Object[] {lease});
            lease.wakeup();
            count++;
        }

        getLogger().info("Woke up {} consumers", new Object[] {count});
    }

    activeLeases.clear();
}