Example usage for java.util.concurrent TimeUnit MINUTES

List of usage examples for java.util.concurrent TimeUnit MINUTES

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit MINUTES.

Prototype

TimeUnit MINUTES

To view the source code for java.util.concurrent TimeUnit MINUTES.

Click Source Link

Document

Time unit representing sixty seconds.

Usage

From source file:me.realized.tm.utilities.profile.UUIDFetcher.java

/**
 * Makes a request to mojang's servers of a sublist of at most 100 player's
 * names. Additionally can provide progress outputs
 *
 * @param output   Whether or not to print output
 * @param log      The {@link Logger} to print to
 * @param doOutput A {@link Predicate} representing when to output a number
 * @return A {@link Map} of player names to their {@link UUID}s
 * @throws IOException          If there's a problem sending or receiving the request
 * @throws ParseException       If the request response cannot be read
 * @throws InterruptedException If the thread is interrupted while sleeping
 * @version 0.1.0/*from www. j av  a  2  s  . c o  m*/
 * @since 0.0.1
 */
public Map<String, UUID> callWithProgressOutput(boolean output, Logger log, Predicate<? super Integer> doOutput)
        throws IOException, ParseException, InterruptedException {
    Map<String, UUID> uuidMap = new HashMap<>();
    int totalNames = this.names.size();
    int completed = 0;
    int failed = 0;
    int requests = (int) Math.ceil(this.names.size() / UUIDFetcher.PROFILES_PER_REQUEST);
    for (int i = 0; i < requests; i++) {
        List<String> request = names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()));
        String body = JSONArray.toJSONString(request);
        HttpURLConnection connection = UUIDFetcher.createConnection();
        UUIDFetcher.writeBody(connection, body);
        if (connection.getResponseCode() == 429 && this.rateLimiting) {
            String out = "[UUIDFetcher] Rate limit hit! Waiting 10 minutes until continuing conversion...";
            if (log != null) {
                log.warning(out);
            } else {
                Bukkit.getLogger().warning(out);
            }
            Thread.sleep(TimeUnit.MINUTES.toMillis(10));
            connection = UUIDFetcher.createConnection();
            UUIDFetcher.writeBody(connection, body);
        }

        JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
        completed += array.size();
        failed += request.size() - array.size();

        for (Object profile : array) {
            JSONObject jsonProfile = (JSONObject) profile;
            UUID uuid = UUIDFetcher.getUUID((String) jsonProfile.get("id"));
            uuidMap.put((String) jsonProfile.get("name"), uuid);
        }

        if (output) {
            int processed = completed + failed;
            if (doOutput.apply(processed) || processed == totalNames) {
                if (log != null) {
                    log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed,
                            totalNames, ((double) processed / totalNames) * 100D, failed));
                }
            }
        }
    }
    return uuidMap;
}

From source file:com.blacklocus.qs.worker.QSAssembly.java

/**
 * @return a configured QueueReader to process tasks. The QueueReader must be started via {@link QueueReader#run()}.
 *///from ww w .  j  a  v  a 2 s  . co m
public QueueReader build() {
    validate();

    Runnable heartbeater = Runnables
            .newInfiniteLoggingRunnable(new QSWorkerHeartbeater(workerIdService, logService));
    new Thread(heartbeater, "WorkerHeartbeater").start();

    configuration.addConfiguration(QSConfig.DEFAULTS);

    QueueingStrategy<QSTaskModel> queueingStrategy = QueueingStrategies.newHeapQueueingStrategy(
            configuration.getDouble(QSConfig.PROP_HEAP_STRATEGY_TRIGGER),
            configuration.getLong(QSConfig.PROP_HEAP_STRATEGY_MAX_DELAY),
            configuration.getLong(QSConfig.PROP_HEAP_STRATEGY_HINT));
    QSTaskService taskService = new ThreadedFIFOQSTaskService(queueingStrategy, taskServices);
    TaskServiceIterable taskIterable = new TaskServiceIterable(taskService);

    ExecutorService workerExecutorService = StrategicExecutors.newBalancingThreadPoolExecutor(
            new ThreadPoolExecutor(configuration.getInt(QSConfig.PROP_WORKER_POOL_CORE),
                    configuration.getInt(QSConfig.PROP_WORKER_POOL_MAX), 1, TimeUnit.MINUTES,
                    new SynchronousQueue<Runnable>(), new CallerBlocksPolicy()),
            configuration.getFloat(QSConfig.PROP_WORKER_POOL_UTILIZATION), DEFAULT_SMOOTHING_WEIGHT,
            DEFAULT_BALANCE_AFTER);

    return new QueueReader<QSTaskModel, TaskKit, Object>(taskIterable,
            new WorkerQueueItemHandler(queueingStrategy, taskService, logService, workerIdService, workers),
            workerExecutorService, 0);
}

From source file:com.amazonaws.codepipeline.jobworker.JobWorkerDaemonTest.java

@Test
public void shouldStopSchedulingJobPoller() throws Exception {
    // given//from w w  w . j  a  v a  2  s  .  co  m
    when(executorService.awaitTermination(1, TimeUnit.MINUTES)).thenReturn(true);

    // when
    jobWorkerDaemon.stop();

    // then
    verify(executorService).shutdown();
}

From source file:com.ottogroup.bi.spqr.pipeline.queue.chronicle.DefaultStreamingMessageQueue.java

/**
 * @see com.ottogroup.bi.spqr.pipeline.queue.StreamingMessageQueue#initialize(java.util.Properties)
 *//*from   w  w w  .ja  va2  s.c  om*/
public void initialize(Properties properties) throws RequiredInputMissingException {

    ////////////////////////////////////////////////////////////////////////////////
    // extract and validate input
    if (properties == null)
        throw new RequiredInputMissingException("Missing required properties");

    if (StringUtils.isBlank(this.id))
        throw new RequiredInputMissingException("Missing required queue identifier");

    if (StringUtils.equalsIgnoreCase(
            StringUtils.trim(properties.getProperty(CFG_CHRONICLE_QUEUE_DELETE_ON_EXIT)), "false"))
        this.deleteOnExit = false;

    this.basePath = StringUtils.lowerCase(StringUtils.trim(properties.getProperty(CFG_CHRONICLE_QUEUE_PATH)));
    if (StringUtils.isBlank(this.basePath))
        this.basePath = System.getProperty("java.io.tmpdir");

    String tmpCycleFormat = StringUtils
            .trim(properties.getProperty(CFG_CHRONICLE_QUEUE_CYCLE_FORMAT, "yyyy-MM-dd-HH-mm"));
    if (StringUtils.isNotBlank(tmpCycleFormat))
        this.cycleFormat = tmpCycleFormat;

    String pathToChronicle = this.basePath;
    if (!StringUtils.endsWith(pathToChronicle, File.separator))
        pathToChronicle = pathToChronicle + File.separator;
    pathToChronicle = pathToChronicle + id;

    try {
        this.queueRollingInterval = TimeUnit.MINUTES.toMillis(
                Long.parseLong(StringUtils.trim(properties.getProperty(CFG_CHRONICLE_QUEUE_ROLLING_INTERVAL))));

        if (this.queueRollingInterval < VanillaChronicle.MIN_CYCLE_LENGTH) {
            this.queueRollingInterval = VanillaChronicle.MIN_CYCLE_LENGTH;
        }
    } catch (Exception e) {
        logger.info("Invalid queue rolling interval found: " + e.getMessage() + ". Using default: "
                + TimeUnit.MINUTES.toMillis(60));
    }

    this.queueWaitStrategy = getWaitStrategy(
            StringUtils.trim(properties.getProperty(CFG_QUEUE_MESSAGE_WAIT_STRATEGY)));

    //
    ////////////////////////////////////////////////////////////////////////////////

    // clears the queue if requested 
    if (this.deleteOnExit) {
        ChronicleTools.deleteDirOnExit(pathToChronicle);
        ChronicleTools.deleteOnExit(pathToChronicle);
    }

    try {
        this.chronicle = ChronicleQueueBuilder.vanilla(pathToChronicle)
                .cycleLength((int) this.queueRollingInterval).cycleFormat(this.cycleFormat).build();
        this.queueConsumer = new DefaultStreamingMessageQueueConsumer(this.getId(),
                this.chronicle.createTailer(), this.queueWaitStrategy);
        this.queueProducer = new DefaultStreamingMessageQueueProducer(this.getId(),
                this.chronicle.createAppender(), this.queueWaitStrategy);
    } catch (IOException e) {
        throw new RuntimeException(
                "Failed to initialize chronicle at '" + pathToChronicle + "'. Error: " + e.getMessage());
    }

    logger.info("queue[type=chronicle, id=" + this.id + ", deleteOnExist=" + this.deleteOnExit + ", path="
            + pathToChronicle + "']");
}

From source file:com.mobilecashout.osprey.remote.RemoteClient.java

private synchronized void executeInParallel(RemoteRunnable runnable, DeploymentContext context,
        String[] roles) {/*from w ww  .j av a2  s . co  m*/
    if (null == roles) {
        roles = new String[] { "all" };
    }
    while (!semaphore.tryAcquire()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            context.setFailed();
            throw new RuntimeException(e);
        }
    }

    final ExecutorService pool = Executors.newFixedThreadPool(sessions.size());
    final ArrayList<Future<Boolean>> futures = new ArrayList<>();

    for (RemoteTarget remoteTarget : sessions) {
        if (!remoteTarget.getTarget().hasAnyRole(roles)) {
            continue;
        }
        Future<Boolean> executor = pool.submit(() -> {
            runnable.run(remoteTarget, context);
            return true;
        });
        futures.add(executor);
    }

    pool.shutdown();

    try {
        pool.awaitTermination(Integer.MAX_VALUE, TimeUnit.MINUTES);
        for (Future future : futures) {
            future.get();
        }
        Thread.sleep(100);
    } catch (InterruptedException | ExecutionException e) {
        context.setFailed();
        logger.fatal(e.getMessage(), e);
    } finally {
        semaphore.release();
    }
}

From source file:com.janrain.backplane2.server.config.Backplane2Config.java

@SuppressWarnings({ "UnusedDeclaration" })
private Backplane2Config() {
    this.bpInstanceId = getAwsProp(InitSystemProps.AWS_INSTANCE_ID);

    ConsoleReporter.enable(10, TimeUnit.MINUTES);

    // Dump metrics to graphite server
    String graphiteServer = System.getProperty(BackplaneSystemProps.GRAPHITE_SERVER);
    if (StringUtils.isNotBlank(graphiteServer)) {
        try {/*from ww w.  jav a 2 s.co  m*/
            String args[] = graphiteServer.split(":");
            String server = args[0];
            int port = Integer.parseInt(args[1]);
            GraphiteReporter.enable(10, TimeUnit.SECONDS, server, port,
                    BackplaneSystemProps.getMachineName().replace(".", "_") + "_" + bpInstanceId);
            logger.info("Graphite server enabled at " + graphiteServer);
        } catch (Exception e) {
            logger.warn(
                    "could not enable Graphite from " + graphiteServer + " must be in the form SERVER:PORT");
        }
    }
    try {
        buildProperties.load(Backplane2Config.class.getResourceAsStream(BUILD_PROPERTIES));
        //assert(StringUtils.isNotBlank(getEncryptionKey()));
    } catch (Exception e) {
        String err = "Error loading build properties from " + BUILD_PROPERTIES;
        logger.error(err, e);
        throw new RuntimeException(err, e);
    }

    logger.info("Configured Backplane Server instance: " + bpInstanceId);
}

From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java

/**
 * Makes a request to mojang's servers of a sublist of at most 100 player's
 * names. Additionally can provide progress outputs
 * //from  ww  w  .java  2s.c om
 * @since 0.0.1
 * @version 0.1.0
 * 
 * @param output Whether or not to print output
 * @param log The {@link Logger} to print to
 * @param doOutput A {@link Predicate} representing when to output a number
 * @return A {@link Map} of player names to their {@link UUID}s
 * @throws IOException If there's a problem sending or receiving the request
 * @throws ParseException If the request response cannot be read
 * @throws InterruptedException If the thread is interrupted while sleeping
 */
public Map<String, UUID> callWithProgessOutput(boolean output, Logger log, Predicate<? super Integer> doOutput)
        throws IOException, ParseException, InterruptedException {
    //Method start
    Map<String, UUID> uuidMap = new HashMap<>();
    int totalNames = this.names.size();
    int completed = 0;
    int failed = 0;
    int requests = (int) Math.ceil(this.names.size() / UUIDFetcher.PROFILES_PER_REQUEST);
    for (int i = 0; i < requests; i++) {
        List<String> request = names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()));
        String body = JSONArray.toJSONString(request);
        HttpURLConnection connection = UUIDFetcher.createConnection();
        UUIDFetcher.writeBody(connection, body);
        if (connection.getResponseCode() == 429 && this.rateLimiting) {
            log.warning("[UUIDFetcher] Rate limit hit! Waiting 10 minutes until continuing conversion...");
            Thread.sleep(TimeUnit.MINUTES.toMillis(10));
            connection = UUIDFetcher.createConnection();
            UUIDFetcher.writeBody(connection, body);
        }
        JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
        completed += array.size();
        failed += request.size() - array.size();
        for (Object profile : array) {
            JSONObject jsonProfile = (JSONObject) profile;
            UUID uuid = UUIDFetcher.getUUID((String) jsonProfile.get("id"));
            uuidMap.put((String) jsonProfile.get("name"), uuid);
        }
        if (output) {
            int processed = completed + failed;
            if (doOutput.test(processed) || processed == totalNames) {
                log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed,
                        totalNames, ((double) processed / totalNames) * 100D, failed));
            }
        }
    }
    return uuidMap;
}

From source file:com.vmware.photon.controller.model.adapters.azure.stats.AzureStatsService.java

private void awaitTermination(ExecutorService executor) {
    try {/*from   w  w w. j a  v a  2s.  c o m*/
        if (!executor.awaitTermination(EXECUTOR_SHUTDOWN_INTERVAL_MINUTES, TimeUnit.MINUTES)) {
            logWarning("Executor service can't be shutdown for Azure. Trying to shutdown now...");
            executor.shutdownNow();
        }
        logFine("Executor service shutdown for Azure");
    } catch (InterruptedException e) {
        logSevere(e);
        Thread.currentThread().interrupt();
    } catch (Exception e) {
        logSevere(e);
    }
}

From source file:edu.cmu.lti.oaqa.bioasq.concept.retrieval.GoPubMedSeparateConceptRetrievalExecutor.java

@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {
    AbstractQuery aquery = TypeUtil.getAbstractQueries(jcas).stream().findFirst().get();
    Collection<QueryConcept> qconcepts = TypeUtil.getQueryConcepts(aquery);
    List<ConceptSearchResult> concepts = Collections.synchronizedList(new ArrayList<>());
    ExecutorService es = Executors.newCachedThreadPool();
    for (QueryConcept qconcept : qconcepts) {
        String queryString = bopQueryStringConstructor.formatQueryConcept(qconcept)
                .replaceAll("[^A-Za-z0-9_\\-\"]+", " ");
        LOG.info("Query string: {}", queryString);
        for (BioASQUtil.Ontology ontology : BioASQUtil.Ontology.values()) {
            es.execute(() -> {/*w  w  w .ja  v  a 2s  .  c  o  m*/
                try {
                    concepts.addAll(
                            BioASQUtil.searchOntology(service, jcas, queryString, pages, hits, ontology));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    es.shutdown();
    try {
        if (!es.awaitTermination(timeout, TimeUnit.MINUTES)) {
            LOG.warn("Timeout occurs for one or some concept retrieval services.");
        }
    } catch (InterruptedException e) {
        throw new AnalysisEngineProcessException(e);
    }
    Map<String, List<ConceptSearchResult>> onto2concepts = concepts.stream()
            .collect(groupingBy(ConceptSearchResult::getSearchId));
    for (Map.Entry<String, List<ConceptSearchResult>> entry : onto2concepts.entrySet()) {
        List<ConceptSearchResult> results = entry.getValue();
        LOG.info("Retrieved {} concepts from {}", results.size(), entry.getKey());
        if (LOG.isDebugEnabled()) {
            results.stream().limit(10).forEach(c -> LOG.debug(" - {}", TypeUtil.toString(c)));
        }
    }
    TypeUtil.rankedSearchResultsByScore(concepts, limit).forEach(ConceptSearchResult::addToIndexes);
}

From source file:it.infn.ct.futuregateway.apiserver.APIContextListener.java

@Override
public final void contextDestroyed(final ServletContextEvent sce) {
    ExecutorService exServ;/*w ww  .j a  v a2 s .  com*/
    try {
        Context ctx = new InitialContext();
        exServ = (ExecutorService) ctx.lookup("java:comp/env/threads/Submitter");
    } catch (NamingException ex) {
        exServ = (ExecutorService) sce.getServletContext().getAttribute("SubmissionThreadPool");
    }
    exServ.shutdown();
    try {
        if (!exServ.awaitTermination(Constants.MAXTHREADWAIT, TimeUnit.MINUTES)) {
            log.warn("Failed to shutdown the submission thread pool.");
        }
    } catch (InterruptedException ex) {
        log.error(ex);
    }
}