Example usage for com.google.common.util.concurrent ListeningExecutorService shutdown

List of usage examples for com.google.common.util.concurrent ListeningExecutorService shutdown

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ListeningExecutorService shutdown.

Prototype

void shutdown();

Source Link

Document

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

Usage

From source file:com.appdynamics.monitors.azure.AzureServiceBusMonitor.java

private void collectAndPrintMetrics(final Configuration config) throws TaskExecutionException {
    final Azure azure = config.getAzure();
    final String metricPrefix = config.getMetricPrefix();
    List<Namespace> namespaces = config.getNamespaces();
    if (namespaces == null || namespaces.isEmpty()) {
        logger.info("No namespaces configured. Please configure namespaces in config.yml file to get stats");
        return;//  w  w w  .j av  a2 s . co m
    }

    ListeningExecutorService namespaceService = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(config.getNamespaceThreads()));
    try {
        for (final Namespace namespace : namespaces) {

            final String namespaceName = namespace.getNamespace();
            if (Strings.isNullOrEmpty(namespaceName)) {
                logger.info("No value for namespaces in configuration. Ignoring the entry");
                continue;
            }

            //Queue Stats
            ListenableFuture<Set<String>> getQueueNames = namespaceService.submit(new Callable<Set<String>>() {
                public Set<String> call() {
                    return getQueueNames(config, namespaceName, namespace.getExcludeQueues());
                }
            });

            Futures.addCallback(getQueueNames, new FutureCallback<Set<String>>() {
                public void onSuccess(Set<String> queueNames) {
                    if (queueNames != null && !queueNames.isEmpty()) {
                        try {
                            Map<String, String> queueStats = azureServiceBusStatsCollector.collectQueueStats(
                                    azure, namespaceName, queueNames, namespace.getQueueStats(),
                                    config.getQueueThreads());
                            printMetrics(queueStats, metricPrefix);
                        } catch (TaskExecutionException e) {
                            logger.error("Unable to get queue stats for namespace [" + namespaceName, e);
                        }
                    }
                }

                public void onFailure(Throwable thrown) {
                    logger.error("Unable to get queues for namespace [" + namespaceName, thrown);
                }
            });

            //Topic stats
            ListenableFuture<Set<String>> getTopicNames = namespaceService.submit(new Callable<Set<String>>() {
                public Set<String> call() {
                    return getTopicNames(config, namespaceName, namespace.getExcludeTopics());
                }
            });

            Futures.addCallback(getTopicNames, new FutureCallback<Set<String>>() {
                public void onSuccess(Set<String> topicNames) {
                    if (topicNames != null && !topicNames.isEmpty()) {
                        try {
                            Map<String, String> topicStats = azureServiceBusStatsCollector.collectTopicStats(
                                    azure, namespaceName, topicNames, namespace.getTopicStats(),
                                    config.getTopicThreads());
                            printMetrics(topicStats, metricPrefix);
                        } catch (TaskExecutionException e) {
                            logger.error("Unable to get topic stats for namespace [" + namespaceName, e);
                        }
                    }
                }

                public void onFailure(Throwable thrown) {
                    logger.error("Unable to get topics for namespace [" + namespaceName, thrown);
                }
            });
        }
    } finally {
        namespaceService.shutdown();
    }
}

From source file:com.github.rinde.datgen.pdptw.DatasetGenerator.java

Dataset<GeneratedScenario> doGenerate() {

    final ListeningExecutorService service = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(builder.numThreads));
    final Dataset<GeneratedScenario> dataset = Dataset.naturalOrder();

    final List<ScenarioCreator> jobs = new ArrayList<>();

    final RandomGenerator rng = new MersenneTwister(builder.randomSeed);
    final Map<GeneratorSettings, IdSeedGenerator> rngMap = new LinkedHashMap<>();

    for (final Long urgency : builder.urgencyLevels) {
        for (final Double scale : builder.scaleLevels) {
            for (final Entry<TimeSeriesType, Collection<Range<Double>>> dynLevel : builder.dynamismLevels
                    .asMap().entrySet()) {

                final int reps = builder.numInstances * dynLevel.getValue().size();

                final long urg = urgency * 60 * 1000L;
                // The office hours is the period in which new orders are accepted,
                // it is defined as [0,officeHoursLength).
                final long officeHoursLength;
                if (urg < halfDiagTT) {
                    officeHoursLength = builder.scenarioLengthMs - twoDiagTT - PICKUP_DURATION
                            - DELIVERY_DURATION;
                } else {
                    officeHoursLength = builder.scenarioLengthMs - urg - oneAndHalfDiagTT - PICKUP_DURATION
                            - DELIVERY_DURATION;
                }/*from w  w w.  j  a  v a  2  s  . c  om*/

                final int numOrders = DoubleMath.roundToInt(scale * numOrdersPerScale,
                        RoundingMode.UNNECESSARY);

                final ImmutableMap.Builder<String, String> props = ImmutableMap.builder();

                props.put("expected_num_orders", Integer.toString(numOrders));
                props.put("pickup_duration", Long.toString(PICKUP_DURATION));
                props.put("delivery_duration", Long.toString(DELIVERY_DURATION));
                props.put("width_height", String.format("%1.1fx%1.1f", AREA_WIDTH, AREA_WIDTH));

                // TODO store this in TimeSeriesType?
                final RangeSet<Double> rset = TreeRangeSet.create();
                for (final Range<Double> r : dynLevel.getValue()) {
                    rset.add(r);
                }

                // createTimeSeriesGenerator(dynLevel.getKey(), officeHoursLength,
                // numOrders, numOrdersPerScale, props);

                final GeneratorSettings set = GeneratorSettings.builder().setDayLength(builder.scenarioLengthMs)
                        .setOfficeHours(officeHoursLength).setTimeSeriesType(dynLevel.getKey())
                        .setDynamismRangeCenters(builder.dynamismRangeMap.subRangeMap(rset.span()))
                        .setUrgency(urg).setScale(scale).setNumOrders(numOrders).setProperties(props.build())
                        .build();

                final IdSeedGenerator isg = new IdSeedGenerator(rng.nextLong());
                rngMap.put(set, isg);

                for (int i = 0; i < reps; i++) {
                    final LocationGenerator lg = Locations.builder().min(0d).max(AREA_WIDTH).buildUniform();

                    final TimeSeriesGenerator tsg2 = createTimeSeriesGenerator(dynLevel.getKey(),
                            officeHoursLength, numOrders, numOrdersPerScale,
                            ImmutableMap.<String, String>builder());
                    final ScenarioGenerator gen = createGenerator(officeHoursLength, urg, scale, tsg2,
                            set.getDynamismRangeCenters(), lg, builder, numOrdersPerScale);

                    jobs.add(ScenarioCreator.create(isg.next(), set, gen));
                }
            }
        }
    }

    final AtomicLong currentJobs = new AtomicLong(0L);
    final AtomicLong datasetSize = new AtomicLong(0L);

    LOGGER.info(" - Submitting " + jobs.size() + " Jobs");
    for (final ScenarioCreator job : jobs) {
        submitJob(currentJobs, service, job, builder.numInstances, dataset, rngMap, datasetSize);
    }

    final long targetSize = builder.numInstances * builder.dynamismLevels.values().size()
            * builder.scaleLevels.size() * builder.urgencyLevels.size();
    while (datasetSize.get() < targetSize || dataset.size() < targetSize) {
        try {
            // LOGGER.info(" - Waiting, current size ==" + dataset.size());
            Thread.sleep(THREAD_SLEEP_DURATION);
        } catch (final InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

    LOGGER.info(" - Shutdown Service, Awaiting Termination");
    service.shutdown();
    try {
        service.awaitTermination(1L, TimeUnit.HOURS);
    } catch (final InterruptedException e) {
        throw new IllegalStateException(e);
    }

    LOGGER.info(" - Returning dataset");

    return dataset;
}