类java.util.concurrent.TimeUnit源码实例Demo

下面列出了怎么用java.util.concurrent.TimeUnit的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: android-test   文件: EventInjectorTest.java
@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]));
}
 
源代码2 项目: etf-webapp   文件: TestRunController.java
@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!");
}
 
@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);

}
 
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();
    }
}
 
源代码5 项目: activemq-artemis   文件: AmqpReceiver.java
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);
}
 
源代码6 项目: emodb   文件: ScanUploadSchedulingService.java
/**
 * 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);
}
 
源代码7 项目: mysql_perf_analyzer   文件: AutoScanner.java
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.");
	
	
}
 
源代码8 项目: micro-integrator   文件: VFSTransportTestCase.java
@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]"));
}
 
源代码9 项目: akarnokd-misc   文件: SingleConcatTest.java
@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
}
 
源代码10 项目: Javacord   文件: DiscordApiBuilderDelegateImpl.java
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());
}
 
源代码11 项目: rya   文件: KafkaNotificationProvider.java
@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");
    }
}
 
@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);
        }
    };
}
 
源代码13 项目: reactor-pool   文件: SimpleLifoPoolTest.java
@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-");
}
 
源代码14 项目: examples   文件: BatchWriter.java
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;
  }
}
 
源代码15 项目: Onosendai   文件: SaveScrollNow.java
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;
		}
	}
}
 
源代码16 项目: activemq-artemis   文件: AbortSlowConsumer1Test.java
@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());
}
 
源代码17 项目: arcusplatform   文件: VoicePlaceSelectionHandler.java
@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);
   }
}
 
源代码18 项目: teku   文件: BLSBenchmark.java
@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();
}
 
源代码19 项目: orianna   文件: FixedWindowRateLimiter.java
@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));
    }
}
 
/**
 * 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();
    }
}
 
源代码21 项目: otroslogviewer   文件: LoadingRunnableTest.java
@Test(invocationCount = 5)
public void testLoadingStopWithLogParser() throws IOException {
  saveLines(Range.closed(0, julSimpleLogLines.size()), julSimpleLogLines, outputStream);

  underTest = createLoadingRunnable(getJulLogParser());
  executorService.submit(underTest);

  await().until(() -> collector.getCount() == 1000);
  underTest.stop();
  saveLines(Range.closed(0, julSimpleLogLines.size()), julSimpleLogLines, outputStream);
  await().atLeast(100, TimeUnit.MILLISECONDS).until(() -> collector.getCount() == 1000);
}
 
@Override
public void run() {
  try {
    while (!this.shutdown) {
      synchronized (this) {
        wait(this.checkWaitTime);
        this.connMgr.closeExpiredConnections();
        this.connMgr.closeIdleConnections(this.idleConnTimeout, TimeUnit.MILLISECONDS);
      }
    }
  } catch (InterruptedException ignore) {
  }
}
 
源代码23 项目: triava   文件: CacheTest.java
private static Cache<String, Integer> createCache(String id, int idleTime, int cacheTime, int size) {
    Builder<String, Integer> cacheB = TCacheFactory.standardFactory().builder();
    cacheB.setId(id);
    cacheB.setMaxIdleTime(idleTime, TimeUnit.SECONDS)
            .setMaxCacheTime(cacheTime, TimeUnit.SECONDS)
            .setMaxElements(size);

    return cacheB.build();
}
 
源代码24 项目: spectator   文件: CompositeTimer.java
@Override public <T> T record(Callable<T> f) throws Exception {
  final long s = clock.monotonicTime();
  try {
    return f.call();
  } finally {
    final long e = clock.monotonicTime();
    record(e - s, TimeUnit.NANOSECONDS);
  }
}
 
public void checkThread() {
    try {
        while (!stopRequest.await(5000, TimeUnit.MILLISECONDS)) {
            barrierRequest = true;
            barrier.await();

            assertConsistent(cache);
            inc("consistency check passed");

            barrier.await();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
源代码26 项目: vlingo-actors   文件: TestUntil.java
public boolean completesWithin(final long timeout) {
  try {
    latch.await(timeout,TimeUnit.MILLISECONDS);
    return latch.getCount() == 0;
  } catch (Exception e) {
    return false;
  }
}
 
源代码27 项目: cyclops   文件: BatchingTest.java
@Test
public void windowBySizeAndTimeSizeEmpty(){

	assertThat(of()
					.groupedBySizeAndTime(3,10,TimeUnit.SECONDS)
					.toList()
					.size(),is(0));
}
 
源代码28 项目: L2jBrasil   文件: ThreadPoolManager.java
private ThreadPoolManager()
{
	_effectsScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_EFFECTS, new PriorityThreadFactory("EffectsSTPool", Thread.NORM_PRIORITY));
	_generalScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_GENERAL, new PriorityThreadFactory("GerenalSTPool", Thread.NORM_PRIORITY));
	_ioPacketsThreadPool = new ThreadPoolExecutor(Config.IO_PACKET_THREAD_CORE_SIZE, Integer.MAX_VALUE,5L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(),new PriorityThreadFactory("I/O Packet Pool",Thread.NORM_PRIORITY+1));
	_generalPacketsThreadPool = new ThreadPoolExecutor(Config.GENERAL_PACKET_THREAD_CORE_SIZE, Config.GENERAL_PACKET_THREAD_CORE_SIZE+2,15L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(),new PriorityThreadFactory("Normal Packet Pool",Thread.NORM_PRIORITY+1));
	_generalThreadPool = new ThreadPoolExecutor(Config.GENERAL_THREAD_CORE_SIZE, Config.GENERAL_THREAD_CORE_SIZE+2,5L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(),new PriorityThreadFactory("General Pool",Thread.NORM_PRIORITY));
	// will be really used in the next AI implementation.
	_aiThreadPool = new ThreadPoolExecutor(1, Config.AI_MAX_THREAD,10L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
	_aiScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.AI_MAX_THREAD, new PriorityThreadFactory("AISTPool", Thread.NORM_PRIORITY));
}
 
源代码29 项目: hawkular-alerts   文件: PartitionManagerImpl.java
@Override
@SuppressWarnings("unchecked")
public void notifyData(Collection<Data> data) {
    if (distributed) {
        NotifyData nData = new NotifyData(currentNode, data, Data.class);
        Integer key = nData.hashCode();
        log.debugf("Sending data [%s]", nData);
        dataCache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES)
                .putAsync(key, nData, LIFESPAN, TimeUnit.MILLISECONDS);
    }
}
 
源代码30 项目: Anti-recall   文件: LoginFragment.java
private boolean verifyCaptcha(String captcha) {
    RequestQueue queue = Volley.newRequestQueue(getContext());
    RequestFuture future = RequestFuture.newFuture();
    StringRequest request = new StringRequest(Request.Method.POST,
            "http://ar.qsboy.com/j/verifyCaptcha", future, future) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> map = new HashMap<>();
            map.put("phone", phone);
            map.put("captcha", captcha);
            return map;
        }
    };

    queue.add(request);

    try {
        String s = (String) future.get(5, TimeUnit.SECONDS);
        boolean isValid = s != null && s.length() > 0;
        if (isValid) {
            Gson gson = new Gson();
            gson.fromJson(s, App.User.class);
        }
        return isValid;
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        e.printStackTrace();
        return false;
    }
}
 
 类所在包
 同包方法