Java Code Examples for java.util.concurrent.TimeUnit

The following examples show how to use java.util.concurrent.TimeUnit. 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: android-test   Author: android   File: EventInjectorTest.java    License: 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 #2
Source Project: etf-webapp   Author: etf-validator   File: TestRunController.java    License: 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 #3
Source Project: rya   Author: apache   File: RdfCloudTripleStoreSelectivityEvaluationStatisticsTest.java    License: 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 #4
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 #5
Source Project: activemq-artemis   Author: apache   File: AmqpReceiver.java    License: 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 #6
Source Project: emodb   Author: bazaarvoice   File: ScanUploadSchedulingService.java    License: 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 #7
Source Project: mysql_perf_analyzer   Author: yahoo   File: AutoScanner.java    License: 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 #8
Source Project: micro-integrator   Author: wso2   File: VFSTransportTestCase.java    License: 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 Project: akarnokd-misc   Author: akarnokd   File: SingleConcatTest.java    License: 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 #10
Source Project: Javacord   Author: Javacord   File: DiscordApiBuilderDelegateImpl.java    License: 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 Project: rya   Author: apache   File: KafkaNotificationProvider.java    License: 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 #12
Source Project: smallrye-fault-tolerance   Author: smallrye   File: ScheduledExecutorTimeoutWatcher.java    License: 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 #13
Source Project: reactor-pool   Author: reactor   File: SimpleLifoPoolTest.java    License: 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 #14
Source Project: examples   Author: ArchitectingHBase   File: BatchWriter.java    License: 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 #15
Source Project: Onosendai   Author: haku   File: SaveScrollNow.java    License: 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 #16
Source Project: activemq-artemis   Author: apache   File: AbortSlowConsumer1Test.java    License: 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 #17
Source Project: arcusplatform   Author: arcus-smart-home   File: VoicePlaceSelectionHandler.java    License: 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 #18
Source Project: teku   Author: PegaSysEng   File: BLSBenchmark.java    License: 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 #19
Source Project: orianna   Author: meraki-analytics   File: FixedWindowRateLimiter.java    License: 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 #20
Source Project: azure-libraries-for-java   Author: Azure   File: ManageSqlServerKeysWithAzureKeyVaultKey.java    License: 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 #21
Source Project: otroslogviewer   Author: otros-systems   File: LoadingRunnableTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #22
Source Project: weixin-java-tools   Author: DarLiner   File: ApacheHttpDnsClientBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@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) {
  }
}
 
Example #23
Source Project: triava   Author: trivago   File: CacheTest.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #24
Source Project: spectator   Author: Netflix   File: CompositeTimer.java    License: Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example #25
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);
    }
}
 
Example #26
Source Project: vlingo-actors   Author: vlingo   File: TestUntil.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public boolean completesWithin(final long timeout) {
  try {
    latch.await(timeout,TimeUnit.MILLISECONDS);
    return latch.getCount() == 0;
  } catch (Exception e) {
    return false;
  }
}
 
Example #27
Source Project: cyclops   Author: aol   File: BatchingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void windowBySizeAndTimeSizeEmpty(){

	assertThat(of()
					.groupedBySizeAndTime(3,10,TimeUnit.SECONDS)
					.toList()
					.size(),is(0));
}
 
Example #28
Source Project: L2jBrasil   Author: L2jBrasil   File: ThreadPoolManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
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));
}
 
Example #29
Source Project: hawkular-alerts   Author: hawkular   File: PartitionManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #30
Source Project: Anti-recall   Author: JasonQS   File: LoginFragment.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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;
    }
}