Example usage for com.google.common.base Stopwatch elapsed

List of usage examples for com.google.common.base Stopwatch elapsed

Introduction

In this page you can find the example usage for com.google.common.base Stopwatch elapsed.

Prototype

@CheckReturnValue
public long elapsed(TimeUnit desiredUnit) 

Source Link

Document

Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, with any fraction rounded down.

Usage

From source file:benchmarkio.producer.rabbitmq.RabbitMQMessageProducer.java

private void produce(final String topic, final String message) {
    for (int i = 0; i < numberOfMessagesToProduce; i++) {
        try {/*ww  w.jav  a2  s.com*/
            if (log.isDebugEnabled()) {
                log.debug("Publishing message to RabbitMQ topic {}\n{}", topic, message.toString());
            }

            // Start
            final Stopwatch stopwatch = Stopwatch.createStarted();

            channel.basicPublish(topic, "#", null, message.getBytes());

            // End
            stopwatch.stop();
            histogram.recordValue(stopwatch.elapsed(Consts.TIME_UNIT_FOR_REPORTING));

        } catch (final Exception e) {
            log.error("Error publishing message to RabbitMQ topic {}\n{}", topic, message.toString());
        }
    }

    log.info("Finished production of {} messages", numberOfMessagesToProduce);
}

From source file:com.isotrol.impe3.pms.core.support.ObjectsLoader.java

/**
 * Constructor./*from  www .  j  av  a2  s .c  o  m*/
 * @param name Object name for debugging.
 * @param computer Computer function.
 */
private ObjectsLoader(String name, final Function<UUID, T> computer) {
    final CacheLoader<Key, T> loader = new CacheLoader<Key, T>() {
        @Override
        public T load(Key key) throws Exception {
            final Stopwatch w = Stopwatch.createStarted();
            try {
                return computer.apply(key.id);
            } finally {
                long t = w.elapsed(TimeUnit.MILLISECONDS);
                if (t > 500) {
                    System.out
                            .println(String.format("State Loader [%s] took %d ms", ObjectsLoader.this.name, t));
                }
            }
        }
    };
    if (StringUtils.hasText(name)) {
        this.name = name;
    } else {
        this.name = computer.toString();
    }
    this.cache = CacheBuilder.newBuilder().maximumSize(64L).softValues()
            .expireAfterAccess(2 * 3600L, TimeUnit.SECONDS).build(loader);
}

From source file:com.facebook.buck.distributed.DistBuildClientStatsTracker.java

private synchronized void stopTimer(DistBuildClientStat stat) {
    Preconditions.checkNotNull(stopwatchesByType.get(stat),
            "Cannot stop timer for stat: [" + stat + "] as it was not started.");

    Stopwatch stopwatch = stopwatchesByType.get(stat);
    stopwatch.stop();// ww w. j  av  a2s.  co  m
    long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    durationsMsByType.put(stat, elapsed);
}

From source file:io.flutter.run.daemon.FlutterApp.java

/**
 * Starts shutting down the process.//ww  w.  ja  v  a  2 s  .co  m
 *
 * <p>If possible, we want to shut down gracefully by sending a stop command to the application.
 */
Future shutdownAsync() {
    final FutureTask done = new FutureTask<>(() -> null);
    if (!changeState(State.TERMINATING)) {
        done.run();
        return done; // Debounce; already shutting down.
    }

    if (myResume != null) {
        myResume.run();
    }

    final String appId = myAppId;
    if (appId == null) {
        // If it it didn't finish starting up, shut down abruptly.
        myProcessHandler.destroyProcess();
        done.run();
        return done;
    }

    // Do the rest in the background to avoid freezing the Swing dispatch thread.
    AppExecutorUtil.getAppExecutorService().submit(() -> {
        // Try to shut down gracefully. (Need to wait for a response.)
        final Future stopDone = myDaemonApi.stopApp(appId);
        final Stopwatch watch = Stopwatch.createStarted();
        while (watch.elapsed(TimeUnit.SECONDS) < 10 && getState() == State.TERMINATING) {
            try {
                stopDone.get(100, TimeUnit.MILLISECONDS);
                break;
            } catch (TimeoutException e) {
                // continue
            } catch (Exception e) {
                LOG.warn(e);
                break;
            }
        }

        // If it didn't work, shut down abruptly.
        myProcessHandler.destroyProcess();
        done.run();
    });
    return done;
}

From source file:org.graylog2.shared.initializers.InputSetupService.java

@Override
protected void shutDown() throws Exception {
    LOG.debug("Stopping InputSetupService");
    eventBus.unregister(this);

    for (IOState<MessageInput> state : inputRegistry.getRunningInputs()) {
        MessageInput input = state.getStoppable();

        LOG.info("Attempting to close input <{}> [{}].", input.getUniqueReadableId(), input.getName());

        Stopwatch s = Stopwatch.createStarted();
        try {//from w  w w.ja va 2s .c o  m
            input.stop();

            LOG.info("Input <{}> closed. Took [{}ms]", input.getUniqueReadableId(),
                    s.elapsed(TimeUnit.MILLISECONDS));
        } catch (Exception e) {
            LOG.error("Unable to stop input <{}> [{}]: " + e.getMessage(), input.getUniqueReadableId(),
                    input.getName());
        } finally {
            s.stop();
        }
    }
    LOG.debug("Stopped InputSetupService");
}

From source file:org.apache.eagle.alert.coordinator.trigger.ScheduleStateCleaner.java

@Override
public void run() {
    // we should catch every exception to avoid zombile thread
    try {//from  w w w  .j av  a  2 s . c  om
        final Stopwatch watch = Stopwatch.createStarted();
        LOG.info("clear schedule states start.");
        client.clearScheduleState(reservedCapacity);
        watch.stop();
        LOG.info("clear schedule states completed. used time milliseconds: {}",
                watch.elapsed(TimeUnit.MILLISECONDS));
        // reset cached policies
    } catch (Throwable t) {
        LOG.error("fail to clear schedule states due to {}, but continue to run", t.getMessage());
    }
}

From source file:pro.foundev.examples.spark_streaming.java.interactive.smartconsumer.DeduplicatingRabbitMQConsumer.java

public void run() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    try {//from www  . j  a v a  2 s.c  o  m
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(EXCHANGE_NAME, true, consumer);
        Set<String> messages = new HashSet<>();
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.start();
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            messages.add(message);

            if (stopwatch.elapsed(TimeUnit.MILLISECONDS) > 1000l) {
                System.out.println("it should be safe to submit messages now");
                for (String m : messages) {
                    //notifying user interface
                    System.out.println(m);
                }
                stopwatch.stop();
                stopwatch.reset();
                messages.clear();
            }
            if (messages.size() > 100000000) {
                System.out.println("save off to file system and clear before we lose everything");
                messages.clear();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.google.pubsub.clients.kafka.KafkaPublisherTask.java

@Override
public void run() {
    Stopwatch stopwatch = Stopwatch.createUnstarted();
    Callback callback = (metadata, exception) -> {
        if (exception != null) {
            log.error(exception.getMessage(), exception);
            return;
        }/*from  w  w w  .  jav a  2 s  .c  o  m*/
        addNumberOfMessages(1);
        metricsHandler.recordLatency(stopwatch.elapsed(TimeUnit.MILLISECONDS));
    };
    stopwatch.start();
    for (int i = 0; i < batchSize; i++) {
        publisher.send(new ProducerRecord<>(topic, null, System.currentTimeMillis(), null, payload), callback);
    }
    publisher.flush();
    stopwatch.stop();
}

From source file:com.facebook.buck.distributed.ThriftCoordinatorClient.java

public ThriftCoordinatorClient start() throws IOException {
    transport = new TFramedTransport(new TSocket(remoteHost, remotePort));

    Stopwatch stopwatch = Stopwatch.createStarted();
    while (true) {
        try {//from w  w w . ja va  2 s  .c o  m
            transport.open();
            break;
        } catch (TTransportException e) {
            if (stopwatch.elapsed(TimeUnit.SECONDS) > MAX_CONNECT_TIMEOUT_SECONDS) {
                throw new IOException(
                        String.format("Failed to connect. Coordinator is still not healthy after [%d] seconds.",
                                MAX_CONNECT_TIMEOUT_SECONDS));
            }

            LOG.debug("Coordinator server currently not available. Retrying in a bit...");
            try {
                Thread.sleep(TimeUnit.SECONDS.toMillis(RETRY_TIMEOUT_SECONDS));
            } catch (InterruptedException innerException) {
                throw new RuntimeException(innerException);
            }
        }
    }

    TProtocol protocol = new TBinaryProtocol(transport);
    client = new CoordinatorService.Client(protocol);
    return this;
}

From source file:eu.europa.ec.fisheries.uvms.rules.service.bean.MDRCache.java

public List<ObjectRepresentation> getEntry(MDRAcronymType acronymType) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<ObjectRepresentation> result = emptyList();
    if (acronymType != null) {
        result = cache.getUnchecked(acronymType);
    }/*w  w w  . jav  a 2 s  . c  o m*/

    long elapsed = stopwatch.elapsed(TimeUnit.SECONDS);
    if (elapsed > 0.25) {
        log.info("Loading " + acronymType + " took " + stopwatch);
    }

    return result;
}