com.google.common.base.Stopwatch Java Examples

The following examples show how to use com.google.common.base.Stopwatch. 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 File: BGPPeer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public synchronized FluentFuture<? extends CommitInfo> releaseConnection() {
    LOG.info("Closing session with peer");
    this.sessionUp = false;
    this.adjRibOutListenerSet.values().forEach(AdjRibOutListener::close);
    this.adjRibOutListenerSet.clear();
    final FluentFuture<? extends CommitInfo> future;
    if (!isRestartingGracefully()) {
        future = terminateConnection();
    } else {
        final Set<TablesKey> gracefulTables = getGracefulTables();
        this.ribWriter.storeStaleRoutes(gracefulTables);
        future = this.ribWriter.clearTables(Sets.difference(this.tables, gracefulTables));
        if (isPeerRestarting()) {
            this.peerRestartStopwatch = Stopwatch.createStarted();
            handleRestartTimer();
        }
    }
    releaseBindingChain();

    closeSession();
    return future;
}
 
Example #2
Source File: InternalSubchannel.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
InternalSubchannel(List<EquivalentAddressGroup> addressGroups, String authority, String userAgent,
    BackoffPolicy.Provider backoffPolicyProvider,
    ClientTransportFactory transportFactory, ScheduledExecutorService scheduledExecutor,
    Supplier<Stopwatch> stopwatchSupplier, SynchronizationContext syncContext, Callback callback,
    InternalChannelz channelz, CallTracer callsTracer, ChannelTracer channelTracer,
    InternalLogId logId, TimeProvider timeProvider) {
  Preconditions.checkNotNull(addressGroups, "addressGroups");
  Preconditions.checkArgument(!addressGroups.isEmpty(), "addressGroups is empty");
  checkListHasNoNulls(addressGroups, "addressGroups contains null entry");
  this.addressIndex = new Index(
      Collections.unmodifiableList(new ArrayList<>(addressGroups)));
  this.authority = authority;
  this.userAgent = userAgent;
  this.backoffPolicyProvider = backoffPolicyProvider;
  this.transportFactory = transportFactory;
  this.scheduledExecutor = scheduledExecutor;
  this.connectingTimer = stopwatchSupplier.get();
  this.syncContext = syncContext;
  this.callback = callback;
  this.channelz = channelz;
  this.callsTracer = callsTracer;
  this.channelTracer = Preconditions.checkNotNull(channelTracer, "channelTracer");
  this.logId = Preconditions.checkNotNull(logId, "logId");
  this.channelLogger = new ChannelLoggerImpl(channelTracer, timeProvider);
}
 
Example #3
Source File: TestingClock.java    From Java_MVVM_with_Swing_and_RxJava_Examples with Apache License 2.0 6 votes vote down vote up
public void awaitTime(long time, long timeoutMs) throws TimeoutException {
    System.out.println("Thread '" + Thread.currentThread().getName() + "' is waiting for time: " + time);

    Stopwatch stopWatch = Stopwatch.createStarted();
    Stopwatch showLifeSignStopWatch = Stopwatch.createStarted();

    while (internalTime.get() < time) {
        sleep_a_little_while();
        checkTimeout(timeoutMs, stopWatch);
        if (showLifeSignStopWatch.elapsed(TimeUnit.SECONDS) >= 1) {
            showLifeSignStopWatch = Stopwatch.createStarted();
            System.out.println("Thread '" + Thread.currentThread().getName() + "' is still waiting for time: " + time);
        }
    }

    System.out.println("Time " + time + " arrived for Thread '" + Thread.currentThread().getName() + "'");
}
 
Example #4
Source File: FAIDACore.java    From metanome-algorithms with Apache License 2.0 6 votes vote down vote up
private List<SimpleInd> checkCandidates(List<SimpleInd> candidates) {
    Stopwatch sw = Stopwatch.createStarted();
    List<SimpleInd> result = new ArrayList<>();
    logger.info("checking: {} candidates on level {}", Integer.valueOf(candidates.size()),
    		Integer.valueOf(candidates.get(0).size()));
    int candidateCount = 0;
    for (SimpleInd candidate : candidates) {
        if (inclusionTester.isIncludedIn(candidate.left, candidate.right)) {
            result.add(candidate); // add result
        }
        candidateCount++;
        if ((candidates.size() > 1000 && candidateCount % (candidates.size() / 20) == 0) ||
                (candidates.size() <= 1000 && candidateCount % 100 == 0)) {
            logger.info("{}/{} candidates checked", Integer.valueOf(candidateCount), Integer.valueOf(candidates.size()));
        }
    }
    logger.info("Time checking candidates on level {}: {}ms, INDs found: {}",
    		Integer.valueOf(candidates.get(0).size()),
    		Long.valueOf(sw.elapsed(TimeUnit.MILLISECONDS)), Integer.valueOf(result.size()));
    return result;
}
 
Example #5
Source File: TestWinrmCommandTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailFastIfNoCommand() throws Exception {
    Duration longTimeout = Asserts.DEFAULT_LONG_TIMEOUT;
    
    Map<String, ?> equalsZero = ImmutableMap.of(EQUALS, 0);
    
    TestWinrmCommand test = app.createAndManageChild(EntitySpec.create(TestWinrmCommand.class)
            .configure(TIMEOUT, longTimeout.multiply(2))
            .configure(TARGET_ENTITY, testEntity)
            .configure(ASSERT_STATUS, makeAssertions(equalsZero)));

    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        app.start(ImmutableList.<Location>of());
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception e) {
        // note: sleep(1000) can take a few millis less than 1000ms, according to a stopwatch.
        Asserts.expectedFailureContains(e, "Must specify exactly one of psScript and command");
        Duration elapsed = Duration.of(stopwatch);
        Asserts.assertTrue(elapsed.isShorterThan(longTimeout.subtract(Duration.millis(20))), "elapsed="+elapsed);
    }

    assertEntityFailed(test);
}
 
Example #6
Source File: TaskScenarioBuilder.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public TaskScenarioBuilder moveTask(String targetJobId) {
    String taskId = getTask().getId();
    logger.info("[{}] Moving Task {} to another job {}", discoverActiveTest(), taskId, targetJobId);
    Stopwatch stopWatch = Stopwatch.createStarted();

    TestStreamObserver<Empty> responseObserver = new TestStreamObserver<>();
    jobClient.moveTask(TaskMoveRequest.newBuilder()
                    .setSourceJobId(jobScenarioBuilder.getJobId())
                    .setTargetJobId(targetJobId)
                    .setTaskId(taskId)
                    .build(),
            responseObserver);
    rethrow(() -> responseObserver.awaitDone(TIMEOUT_MS, TimeUnit.MILLISECONDS));

    logger.info("[{}] Task {} moved to job {} in {}[ms]", discoverActiveTest(), taskId, targetJobId, stopWatch.elapsed(TimeUnit.MILLISECONDS));
    return this;
}
 
Example #7
Source File: JsMagmaScriptEvaluatorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Disabled
@Test
void testPerformance() {
  Entity person = new DynamicEntity(personBirthDateMeta);
  person.set("birthdate", now().atOffset(UTC).toLocalDate());

  jsMagmaScriptEvaluator.eval("$('birthdate').age().value()", person);

  Stopwatch sw = Stopwatch.createStarted();
  jsMagmaScriptEvaluator.eval(Collections.nCopies(10000, "$('birthdate').age().value()"), person);
  System.out.println(sw.elapsed(TimeUnit.MILLISECONDS) + " millis passed evalList");

  sw.reset().start();

  for (int i = 0; i < 10000; i++) {
    jsMagmaScriptEvaluator.eval("$('birthdate').age().value()", person);
  }
  System.out.println(
      sw.elapsed(TimeUnit.MILLISECONDS)
          + " millis passed recreating bindings for each evaluation");
}
 
Example #8
Source File: MnemonicCode.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Convert mnemonic word list to seed.
 */
public static byte[] toSeed(List<String> words, String passphrase) {

    // To create binary seed from mnemonic, we use PBKDF2 function
    // with mnemonic sentence (in UTF-8) used as a password and
    // string "mnemonic" + passphrase (again in UTF-8) used as a
    // salt. Iteration count is set to 4096 and HMAC-SHA512 is
    // used as a pseudo-random function. Desired length of the
    // derived key is 512 bits (= 64 bytes).
    //
    String pass = Utils.join(words);
    String salt = "mnemonic" + passphrase;

    final Stopwatch watch = Stopwatch.createStarted();
    byte[] seed = PBKDF2SHA512.derive(pass, salt, PBKDF2_ROUNDS, 64);
    watch.stop();
    log.info("PBKDF2 took {}", watch);
    return seed;
}
 
Example #9
Source File: TraceCollector.java    From glowroot with Apache License 2.0 6 votes vote down vote up
Trace getPartialTrace(int timeout, TimeUnit unit) throws InterruptedException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (stopwatch.elapsed(unit) < timeout) {
        for (Trace trace : traces) {
            if (trace.getHeader().getPartial()) {
                return trace;
            }
        }
        MILLISECONDS.sleep(10);
    }
    if (traces.isEmpty()) {
        throw new IllegalStateException("No trace was collected");
    } else {
        throw new IllegalStateException("Trace was collected but is not partial");
    }
}
 
Example #10
Source File: CachePushConfigVersionServiceImpl.java    From qconfig with MIT License 6 votes vote down vote up
private void freshPushVersionCache() {
    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        logger.info("fresh push version cache");
        List<PushConfigVersionItem> pushItems = pushConfigVersionDao.select();

        ConcurrentMap<Key, Version> newCache = new ConcurrentHashMap<Key, Version>(pushItems.size());
        for (PushConfigVersionItem pushItem : pushItems) {
            newCache.put(new Key(pushItem.getMeta(), pushItem.getIp()), new Version(pushItem.getVersion()));
        }

        this.cache = newCache;
        logger.info("fresh push version cache successOf, count [{}]", pushItems.size());
    } finally {
        Monitor.freshPushVersionCache.update(stopwatch.elapsed().toMillis(), TimeUnit.MILLISECONDS);
    }
}
 
Example #11
Source File: CassandraHealthCheck.java    From emodb with Apache License 2.0 6 votes vote down vote up
private Result pingAll() {
    try {
        StringBuilder message = new StringBuilder();

        OperationResult<CqlStatementResult> astyanaxResult = pingAstyanax();
        message.append("Astyanax: ").append(astyanaxResult.getHost()).append(" ")
                .append(astyanaxResult.getLatency(TimeUnit.MICROSECONDS)).append("us");

        if (astyanaxResult.getAttemptsCount() != 1) {
            message.append(", ").append(astyanaxResult.getAttemptsCount()).append(" attempts");
        }

        Stopwatch cqlTimer = Stopwatch.createStarted();
        ResultSet cqlResult = pingCql();
        long queryDurationMicros = cqlTimer.elapsed(TimeUnit.MICROSECONDS);

        Host host = cqlResult.getExecutionInfo().getQueriedHost();
        message.append(" | CQL: ").append(host).append(" ").append(queryDurationMicros).append("us");

        return Result.healthy(message.toString());
    } catch (Throwable t) {
        return Result.unhealthy(t);
    }
}
 
Example #12
Source File: ASMReflectorTest.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testReflectInterface1() throws Exception {
  ASMReflector asmReflector = ASMReflector.getInstance();
  Stopwatch stopwatch = Stopwatch.createUnstarted();
  {
    String fqcn = "com.google.common.eventbus.SubscriberExceptionHandler";
    File jar = getJar("guava:guava:");
    Map<String, ClassIndex> index = asmReflector.getClassIndexes(jar);
    final InheritanceInfo info = asmReflector.getReflectInfo(index, fqcn);

    stopwatch.start();
    List<MemberDescriptor> memberDescriptors = asmReflector.reflectAll(info);
    System.out.println(stopwatch.stop());
    memberDescriptors.forEach(
        m -> {
          System.out.println(m.getDeclaration());
          System.out.println("Return: " + m.getRawReturnType());
        });
    assertEquals(1, memberDescriptors.size());
    stopwatch.reset();
  }
}
 
Example #13
Source File: RateLimiter.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static final SleepingStopwatch createFromSystemTimer() {
  return new SleepingStopwatch() {
    final Stopwatch stopwatch = Stopwatch.createStarted();

    @Override
    protected long readMicros() {
      return stopwatch.elapsed(MICROSECONDS);
    }

    @Override
    protected void sleepMicrosUninterruptibly(long micros) {
      if (micros > 0) {
        Uninterruptibles.sleepUninterruptibly(micros, MICROSECONDS);
      }
    }
  };
}
 
Example #14
Source File: CheckTestUtil.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
private static <R, T extends DataObject> R readData(final DataBroker dataBroker, final LogicalDatastoreType ldt,
    final InstanceIdentifier<T> iid, final Function<T, R> function, final int timeout)
    throws ExecutionException, InterruptedException {
    AssertionError lastError = null;
    final Stopwatch sw = Stopwatch.createStarted();
    do {
        try (ReadTransaction tx = dataBroker.newReadOnlyTransaction()) {
            final Optional<T> data = tx.read(ldt, iid).get();
            if (data.isPresent()) {
                try {
                    return function.apply(data.get());
                } catch (final AssertionError e) {
                    lastError = e;
                    Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
                }
            }
        }
    } while (sw.elapsed(TimeUnit.SECONDS) <= timeout);
    throw lastError;
}
 
Example #15
Source File: PointMapping.java    From elastic-db-tools-for-java with MIT License 6 votes vote down vote up
/**
 * Performs validation that the local representation is as up-to-date as the representation on the backing data store.
 *
 * @param shardMap
 *            Shard map to which the shard provider belongs.
 * @param conn
 *            Connection used for validation.
 */
@Override
public void validate(StoreShardMap shardMap,
        Connection conn) {
    try {
        log.info("PointMapping Validate Start; Connection: {}", conn.getMetaData().getURL());
        Stopwatch stopwatch = Stopwatch.createStarted();

        ValidationUtils.validateMapping(conn, this.getShardMapManager(), shardMap, this.getStoreMapping());

        stopwatch.stop();

        log.info("PointMapping Validate Complete; Connection: {}; Duration:{}", conn.getMetaData().getURL(),
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
    catch (SQLException e) {
        e.printStackTrace();
        throw (ShardManagementException) e.getCause();
    }
}
 
Example #16
Source File: ElectPrimaryTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
        int count = -1;
        Stopwatch sw = Stopwatch.createStarted();
        while (++count<100) {
            log.info("new test run\n\n\nTEST RUN "+count+"\n");
            
//            ElectPrimaryTest t = new ElectPrimaryTest();
//            t.setUp();
//            t.testFireCausesPromoteDemote();
//            t.tearDown();
            
            TestNG testNG = new TestNG();
            testNG.setTestClasses(new Class[] { ElectPrimaryTest.class });
            testNG.addListener((ITestNGListener)new LoggingVerboseReporter());
            FailedReporter failedReporter = new FailedReporter();
            testNG.addListener((ITestNGListener)failedReporter);
            testNG.run();
            if (!failedReporter.getFailedTests().isEmpty()) {
                log.error("Failures: "+failedReporter.getFailedTests());
                System.exit(1);
            }
        }
        log.info("\n\nCompleted "+count+" runs in "+Duration.of(sw));
    }
 
Example #17
Source File: HiveVarcharTruncationReader.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public void runProjector(BaseVariableWidthVector vector, int recordCount,
                         OperatorContext context,
                         Stopwatch javaCodeGenWatch,
                         Stopwatch gandivaCodeGenWatch) throws Exception {
  if (transferPair == null) {
    return;
  }

  if (castRequired(vector, recordCount, truncLen)) {
    splitter.projectRecords(recordCount, javaCodeGenWatch, gandivaCodeGenWatch);
    context.getStats().addLongStat(ScanOperator.Metric.TOTAL_HIVE_PARQUET_TRUNCATE_VARCHAR, 1);
  } else {
    javaCodeGenWatch.start();
    transferPair.transfer();
    javaCodeGenWatch.stop();
    context.getStats().addLongStat(ScanOperator.Metric.TOTAL_HIVE_PARQUET_TRANSFER_VARCHAR, 1);
  }
  context.getStats().addLongStat(ScanOperator.Metric.HIVE_PARQUET_CHECK_VARCHAR_CAST_TIME,
    varcharCheckCastWatch.elapsed(TimeUnit.NANOSECONDS));
  varcharCheckCastWatch.reset();
}
 
Example #18
Source File: CommonTest.java    From rpcx-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testMap2() {
    ExecutorService pool = Executors.newFixedThreadPool(20);

    ConcurrentHashMap<String, String> m2 = new ConcurrentHashMap<>();
    m2.put("a", "1");

    Stopwatch sw2 = Stopwatch.createStarted();
    IntStream.range(0, 1000000).forEach(i -> {
        try {
            pool.invokeAll(IntStream.range(0, 20).mapToObj(ii -> (Callable<Void>) () -> {
                m2.get("a");
                return null;
            }).collect(Collectors.toList()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    System.out.println(sw2.elapsed(TimeUnit.MILLISECONDS));

}
 
Example #19
Source File: XtendIncrementalBuilderPerformanceTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public void doTestPerformance(final int max) {
  final Procedure1<BuildRequest> _function = (BuildRequest it) -> {
    final Function1<Integer, URI> _function_1 = (Integer it_1) -> {
      return this.toFile((it_1).intValue(), max);
    };
    it.setDirtyFiles(IterableExtensions.<URI>toList(IterableExtensions.<Integer, URI>map(new IntegerRange(1, max), _function_1)));
  };
  final BuildRequest buildRequest = this.newBuildRequest(_function);
  final Stopwatch sw = Stopwatch.createStarted();
  this.build(buildRequest);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append(max);
  _builder.append(" file took ");
  long _elapsed = sw.elapsed(TimeUnit.MILLISECONDS);
  _builder.append(_elapsed);
  _builder.append(" ms");
  InputOutput.<String>println(_builder.toString());
}
 
Example #20
Source File: TestSshCommandTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailFastIfNoCommand() throws Exception {
    Duration longTimeout = Asserts.DEFAULT_LONG_TIMEOUT;
    
    Map<String, ?> equalsZero = ImmutableMap.of(EQUALS, 0);
    
    TestSshCommand test = app.createAndManageChild(EntitySpec.create(TestSshCommand.class)
            .configure(TIMEOUT, longTimeout.multiply(2))
            .configure(TARGET_ENTITY, testEntity)
            .configure(ASSERT_STATUS, makeAssertions(equalsZero)));

    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        app.start(ImmutableList.<Location>of());
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception e) {
        // note: sleep(1000) can take a few millis less than 1000ms, according to a stopwatch.
        Asserts.expectedFailureContains(e, "Must specify exactly one of download.url and command");
        Duration elapsed = Duration.of(stopwatch);
        Asserts.assertTrue(elapsed.isShorterThan(longTimeout.subtract(Duration.millis(20))), "elapsed="+elapsed);
    }

    assertEntityFailed(test);
}
 
Example #21
Source File: AndroidResourceParsingAction.java    From bazel with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(Options.class, ResourceProcessorCommonOptions.class)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  optionsParser.parseAndExitUponError(args);
  Options options = optionsParser.getOptions(Options.class);

  Preconditions.checkNotNull(options.primaryData);
  Preconditions.checkNotNull(options.output);

  final Stopwatch timer = Stopwatch.createStarted();
  ParsedAndroidData parsedPrimary = ParsedAndroidData.from(options.primaryData);
  logger.fine(String.format("Walked XML tree at %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
  UnwrittenMergedAndroidData unwrittenData =
      UnwrittenMergedAndroidData.of(
          null, parsedPrimary, ParsedAndroidData.from(ImmutableList.<DependencyAndroidData>of()));
  AndroidDataSerializer serializer = AndroidDataSerializer.create();
  unwrittenData.serializeTo(serializer);
  serializer.flushTo(options.output);
  logger.fine(
      String.format("Finished parse + serialize in %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
}
 
Example #22
Source File: BKLogWriteHandler.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
/**
 * Finalize a log segment. If the journal manager is currently
 * writing to a ledger, ensure that this is the ledger of the log segment
 * being finalized.
 * <p/>
 * Otherwise this is the recovery case. In the recovery case, ensure that
 * the firstTxId of the ledger matches firstTxId for the segment we are
 * trying to finalize.
 */
LogSegmentMetadata completeAndCloseLogSegment(String inprogressZnodeName, long logSegmentSeqNo,
                                              long ledgerId, long firstTxId, long lastTxId,
                                              int recordCount, long lastEntryId, long lastSlotId)
        throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    boolean success = false;
    try {
        LogSegmentMetadata completedLogSegment =
                doCompleteAndCloseLogSegment(inprogressZnodeName, logSegmentSeqNo,
                        ledgerId, firstTxId, lastTxId, recordCount,
                        lastEntryId, lastSlotId);
        success = true;
        return completedLogSegment;
    } finally {
        if (success) {
            closeOpStats.registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        } else {
            closeOpStats.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        }
    }
}
 
Example #23
Source File: CountdownTimerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public void testNotify() throws InterruptedException {
    CountdownTimer timer = Duration.FIVE_SECONDS.countdownTimer();
    final Object mutex = new Object();
    final Semaphore gun = new Semaphore(0);
    Stopwatch watch = Stopwatch.createStarted();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try { gun.acquire(); } catch (Exception e) { throw Exceptions.propagate(e); }
            synchronized (mutex) {
                mutex.notifyAll();
            }
        }
    }).start();
    synchronized (mutex) {
        gun.release();
        assertTrue(timer.waitOnForExpiry(mutex));
    }
    assertTrue(watch.elapsed(TimeUnit.MILLISECONDS) < 3000, "took too long: "+watch);
}
 
Example #24
Source File: ListShardMap.java    From elastic-db-tools-for-java with MIT License 6 votes vote down vote up
/**
 * Gets all the mappings that exist within given range and given shard.
 *
 * @param range
 *            Point value, any mapping overlapping with the range will be returned.
 * @param shard
 *            Shard for which the mappings will be returned.
 * @return Read-only collection of mappings that satisfy the given range and shard constraints.
 */
public List<PointMapping> getMappings(Range range,
        Shard shard) {
    ExceptionUtils.disallowNullArgument(range, "range");
    ExceptionUtils.disallowNullArgument(shard, "shard");

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        log.info("GetPointMappings", "Start; Shard: {}; Range:{}", shard.getLocation(), range);

        Stopwatch stopwatch = Stopwatch.createStarted();

        List<PointMapping> pointMappings = lsm.getMappingsForRange(range, shard, LookupOptions.LOOKUP_IN_STORE);

        stopwatch.stop();

        log.info("GetPointMappings", "Complete; Shard: {}; Range: {}; Duration:{}", shard.getLocation(),
                stopwatch.elapsed(TimeUnit.MILLISECONDS));

        return pointMappings;
    }
}
 
Example #25
Source File: TransactionManager.java    From phoenix-tephra with Apache License 2.0 6 votes vote down vote up
public void abort(Transaction tx) {
  // guard against changes to the transaction log while processing
  txMetricsCollector.rate("abort");
  Stopwatch timer = new Stopwatch().start();
  this.logReadLock.lock();
  try {
    synchronized (this) {
      ensureAvailable();
      doAbort(tx.getTransactionId(), tx.getCheckpointWritePointers(), tx.getType());
    }
    appendToLog(TransactionEdit.createAborted(tx.getTransactionId(), tx.getType(), tx.getCheckpointWritePointers()));
    txMetricsCollector.histogram("abort.latency", (int) timer.elapsedMillis());
  } finally {
    this.logReadLock.unlock();
  }
}
 
Example #26
Source File: RangeShardMap.java    From elastic-db-tools-for-java with MIT License 6 votes vote down vote up
/**
 * Gets all the range mappings that exist within given range and given shard.
 *
 * @param range
 *            Range value, any mapping overlapping with the range will be returned.
 * @param shard
 *            Shard for which the mappings will be returned.
 * @return Read-only collection of mappings that satisfy the given range and shard constraints.
 */
public List<RangeMapping> getMappings(Range range,
        Shard shard) {
    ExceptionUtils.disallowNullArgument(range, "range");
    ExceptionUtils.disallowNullArgument(shard, "shard");

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        log.info("GetMappings Start; Shard: {}; Range: {}", shard.getLocation(), range);

        Stopwatch stopwatch = Stopwatch.createStarted();

        List<RangeMapping> rangeMappings = this.rsm.getMappingsForRange(range, shard, LookupOptions.LOOKUP_IN_STORE);

        stopwatch.stop();

        log.info("GetMappings Complete; Shard: {}; Duration: {}", shard.getLocation(), stopwatch.elapsed(TimeUnit.MILLISECONDS));

        return rangeMappings;
    }
}
 
Example #27
Source File: AbstractLoadTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
protected Callable<Entity> newProvisionAppTask(final String yaml) {
    return new Callable<Entity>() {
        public Entity call() throws Exception {
            try {
                Stopwatch stopwatch = Stopwatch.createStarted();
                Entity app = createAndStartApplication(yaml);
                Duration duration = Duration.of(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
                LOG.info("Provisioning time: "+duration);
                provisioningTimes.add(duration);

                return app;
            } catch (Throwable t) {
                LOG.error("Error deploying app (rethrowing)", t);
                throw Exceptions.propagate(t);
            }
        }
    };
}
 
Example #28
Source File: AlbumDao.java    From mapr-music with Apache License 2.0 6 votes vote down vote up
/**
 * Returns number of albums according to the specified language.
 *
 * @param language language code.
 * @return number of albums with specified language code.
 */
public long getTotalNumByLanguage(String language) {
    return processStore((connection, store) -> {

        Stopwatch stopwatch = Stopwatch.createStarted();

        QueryCondition languageEqualsCondition = connection.newCondition()
                .is("language", QueryCondition.Op.EQUAL, language)
                .build();

        Query query = connection.newQuery()
                .select("_id")
                .where(languageEqualsCondition)
                .build();

        DocumentStream documentStream = store.findQuery(query);
        long totalNum = 0;
        for (Document ignored : documentStream) {
            totalNum++;
        }

        log.debug("Counting '{}' albums by language '{}' took {}", totalNum, language, stopwatch);

        return totalNum;
    });
}
 
Example #29
Source File: DeterministicKeyChain.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Pre-generate enough keys to reach the lookahead size, but only if there are more than the lookaheadThreshold to
 * be generated, so that the Bloom filter does not have to be regenerated that often.
 *
 * The returned mutable list of keys must be inserted into the basic key chain.
 */
private List<DeterministicKey> maybeLookAhead(DeterministicKey parent, int issued, int lookaheadSize, int lookaheadThreshold) {
    checkState(lock.isHeldByCurrentThread());
    final int numChildren = hierarchy.getNumChildren(parent.getPath());
    final int needed = issued + lookaheadSize + lookaheadThreshold - numChildren;

    if (needed <= lookaheadThreshold)
        return new ArrayList<>();

    log.info("{} keys needed for {} = {} issued + {} lookahead size + {} lookahead threshold - {} num children",
            needed, parent.getPathAsString(), issued, lookaheadSize, lookaheadThreshold, numChildren);

    List<DeterministicKey> result  = new ArrayList<>(needed);
    final Stopwatch watch = Stopwatch.createStarted();
    int nextChild = numChildren;
    for (int i = 0; i < needed; i++) {
        DeterministicKey key = HDKeyDerivation.deriveThisOrNextChildKey(parent, nextChild);
        key = key.dropPrivateBytes();
        hierarchy.putKey(key);
        result.add(key);
        nextChild = key.getChildNumber().num() + 1;
    }
    watch.stop();
    log.info("Took {}", watch);
    return result;
}
 
Example #30
Source File: JsonDecode.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    final Stopwatch watch = Stopwatch.createStarted();

    in.markReaderIndex(); //我们标记一下当前的readIndex的位置
    int dataLength = in.readInt(); // 读取传送过来的消息的长度。ByteBuf 的readInt()方法会让他的readIndex增加4
    byte[] body = new byte[dataLength]; //传输正常
    in.readBytes(body);
    RemotingProtocol o = JSON.parseObject(new String(body, encoding), RemotingProtocol.class); //将byte数据转化为我们需要的对象
    out.add(o);
    logger.info("fastjson decoder use:" + watch.toString());
    
}