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:org.glowroot.agent.init.NettyWorkaround.java

private static void waitForMain(Instrumentation instrumentation) throws InterruptedException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (stopwatch.elapsed(SECONDS) < 60) {
        Thread.sleep(100);/*from  w  w w  .  java2 s. co m*/
        for (Class<?> clazz : instrumentation.getInitiatedClasses(null)) {
            if (clazz.getName().equals("sun.misc.Launcher")) {
                return;
            }
        }
    }
    // something has gone wrong
    startupLogger.error("sun.misc.Launcher was never loaded");
}

From source file:org.apache.beam.sdk.io.synthetic.delay.SyntheticDelay.java

/** Keep cpu busy for {@code delayMillis} by calculating lots of hashes. */
private static void cpuDelay(long delayMillis) {
    // Note that the delay is enforced in terms of walltime. That implies this thread may not
    // keep CPU busy if it gets preempted by other threads. There is more of chance of this
    // occurring in a streaming pipeline as there could be lots of threads running this. The loop
    // measures cpu time spent for each iteration, so that these effects are some what minimized.

    long cpuMicros = delayMillis * 1000;
    Stopwatch timer = Stopwatch.createUnstarted();

    while (timer.elapsed(TimeUnit.MICROSECONDS) < cpuMicros) {
        // Find a long which hashes to HASH in lowest MASK bits.
        // Values chosen to roughly take 1ms on typical workstation.
        timer.start();/*w ww  . j a  v a  2s  .c o  m*/
        long p = INIT_PLAINTEXT;
        while (true) {
            long t = Hashing.murmur3_128().hashLong(p).asLong();
            if ((t & MASK) == (HASH & MASK)) {
                break;
            }
            p++;
        }
        timer.stop();
    }
}

From source file:com.github.nginate.commons.lang.await.Await.java

/**
 * Wait till the condition will become true during at most {@code timeout} millis. Will be checking the condition
 * each {@code waitStepMillis} millis.// ww w  .j  a v  a  2  s  .c  om
 *
 * @param timeout        max wait millis
 * @param waitStepMillis step wait millis
 * @param failureMessage message to see if waiting fails
 * @param condition      required condition
 * @throws ConditionTimeoutException if condition was not satisfied in configured period
 * @throws IllegalArgumentException  if step millis are more or equal to overall wait millis
 */
public static void waitUntil(int timeout, int waitStepMillis, String failureMessage,
        Callable<Boolean> condition) {
    Preconditions.checkArgument(waitStepMillis > 0, "step sleep time should be positive");
    Preconditions.checkArgument(waitStepMillis <= timeout, "step sleep time must be less or equal to timeout");

    Stopwatch stopwatch = Stopwatch.createStarted();
    while (stopwatch.elapsed(MILLISECONDS) < timeout) {
        try {
            if (condition.call()) {
                return;
            }
            sleep(waitStepMillis);
        } catch (Exception e) {
            throw propagate(e);
        }
    }
    throw new ConditionTimeoutException(failureMessage);
}

From source file:com.b2international.commons.time.TimeUtil.java

public static String toString(final Stopwatch watch) {
    return nanoToReadableString(watch.elapsed(NANOSECONDS));
}

From source file:org.glowroot.jvm.LazyPlatformMBeanServer.java

@VisibleForTesting
static void waitForJBossModuleInitialization(Stopwatch stopwatch) throws InterruptedException {
    stopwatch.start();//  w  ww .j a v a 2s.com
    while (stopwatch.elapsed(SECONDS) < 60) {
        if (System.getProperty("java.util.logging.manager") != null) {
            return;
        }
        Thread.sleep(100);
    }
    // something has gone wrong
    logger.error("this jvm appears to be running jboss-modules, but it did not set up"
            + " java.util.logging.manager");
}

From source file:nextmethod.threading.SpinWait.java

public static boolean spinUntil(final Delegates.IFunc<Boolean> condition, final long amount,
        final TimeUnit timeUnit) {
    final SpinWait spinWait = new SpinWait();
    final Stopwatch stopwatch = Stopwatch.createStarted();

    while (!condition.invoke()) {
        if (stopwatch.elapsed(timeUnit) > amount) {
            return false;
        }/*from  w w  w  .j a v a  2s .  co m*/
        spinWait.spinOnce();
    }
    return true;
}

From source file:com.twitter.distributedlog.ZooKeeperClientUtils.java

/**
 * Expire given zookeeper client's session.
 *
 * @param zkc//from  w ww.j  a v a  2  s  .  co  m
 *          zookeeper client
 * @param zkServers
 *          zookeeper servers
 * @param timeout
 *          timeout
 * @throws Exception
 */
public static void expireSession(ZooKeeperClient zkc, String zkServers, int timeout) throws Exception {
    final CountDownLatch expireLatch = new CountDownLatch(1);
    final CountDownLatch latch = new CountDownLatch(1);
    ZooKeeper oldZk = zkc.get();
    oldZk.exists("/", new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            logger.debug("Receive event : {}", event);
            if (event.getType() == Event.EventType.None && event.getState() == Event.KeeperState.Expired) {
                expireLatch.countDown();
            }
        }
    });
    ZooKeeper newZk = new ZooKeeper(zkServers, timeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (Event.EventType.None == event.getType()
                    && Event.KeeperState.SyncConnected == event.getState()) {
                latch.countDown();
            }
        }
    }, oldZk.getSessionId(), oldZk.getSessionPasswd());
    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
    }
    newZk.close();

    boolean done = false;
    Stopwatch expireWait = Stopwatch.createStarted();
    while (!done && expireWait.elapsed(TimeUnit.MILLISECONDS) < timeout * 2) {
        try {
            zkc.get().exists("/", false);
            done = true;
        } catch (KeeperException ke) {
            done = (ke.code() == KeeperException.Code.SESSIONEXPIRED);
        }
    }

    assertTrue("Client should receive session expired event.",
            expireLatch.await(timeout, TimeUnit.MILLISECONDS));
}

From source file:ch.ethz.tik.hrouting.providers.GraphProvider.java

public static Graph loadGraphFromAssets(Context context) {
    startedInit = true;// ww  w  . j  av  a2 s .c o m
    Stopwatch stopwatch = Stopwatch.createStarted();
    graph = GraphSerializerUtil.deSerialize(getBufferedInputStream(context));
    stopwatch.elapsed(TimeUnit.MILLISECONDS);
    Log.i(TAG, "Deserialized graph in " + stopwatch);
    return graph;
}

From source file:org.glowroot.local.ui.LazyHttpServer.java

private static void waitForMain(Instrumentation instrumentation) throws InterruptedException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (stopwatch.elapsed(SECONDS) < 60) {
        Thread.sleep(100);// w  w  w.j  av  a 2  s.  co m
        for (Class<?> clazz : instrumentation.getInitiatedClasses(null)) {
            if (clazz.getName().equals("sun.misc.Launcher")) {
                return;
            }
        }
    }
    // something has gone wrong
    logger.error("sun.launcher.LauncherHelper was never loaded");
}

From source file:org.glowroot.container.impl.JavaagentMain.java

private static void startViewer() throws AssertionError {
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override//from   w w w .  j  ava 2s  .c o m
        public void run() {
            try {
                Viewer.main();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    });
    Stopwatch stopwatch = Stopwatch.createStarted();
    // need to wait longer than expected here when running with jacoco on travis ci boxes
    while (stopwatch.elapsed(SECONDS) < 30) {
        if (MainEntryPoint.getGlowrootModule() != null) {
            break;
        }
    }
    if (MainEntryPoint.getGlowrootModule() == null) {
        throw new AssertionError("Timeout occurred waiting for glowroot to start");
    }
}