List of usage examples for com.google.common.base Stopwatch createStarted
@CheckReturnValue public static Stopwatch createStarted()
From source file:eu.europa.ec.fisheries.uvms.rules.service.bean.RulesEngineBean.java
@SuppressWarnings("unchecked") public List<AbstractFact> evaluate(BusinessObjectType businessObjectType, Object businessObject, Map<ExtraValueType, Object> map) throws RulesValidationException { log.info(String.format("[START] Validating %s ", businessObject.getClass().getSimpleName())); Stopwatch stopwatch = Stopwatch.createStarted(); List<AbstractFact> facts = new ArrayList<>(); AbstractGenerator generator = BusinessObjectFactory.getBusinessObjFactGenerator(businessObjectType); generator.setBusinessObjectMessage(businessObject); mdrCacheService.loadMDRCache();//from w ww .j a va 2s . co m generator.setExtraValueMap(map); generator.setAdditionalValidationObject(); facts.addAll(generator.generateAllFacts()); templateEngine.evaluateFacts(facts); log.info(String.format("[END] It took %s to evaluate the message.", stopwatch)); return facts; }
From source file:org.hawkular.metrics.core.util.GCGraceSecondsManager.java
/** * Asynchronously performs gc_grace_seconds updates if necessary. This method should <strong>not</strong> be called * until schema updates have finished./* ww w. j a v a 2s. c o m*/ */ public void maybeUpdateGCGraceSeconds() { logger.info("Checking tables in " + keyspace + " to see if gc_grace_seconds needs to be updated"); Stopwatch stopwatch = Stopwatch.createStarted(); Map<String, String> replication = session.getCluster().getMetadata().getKeyspace(keyspace).getReplication(); String replicationFactor = replication.get("replication_factor"); Completable check; if (getClusterSize() == 1 || replicationFactor.equals("1")) { check = updateAllGCGraceSeconds(0); } else { // Need to call Completable.merge in order for subscriptions to happen correctly. See https://goo.gl/l15CRV check = Completable.merge(configurationService.load("org.hawkular.metrics", "gcGraceSeconds") .switchIfEmpty(Observable.just(Integer.toString(DEFAULT_GC_GRACE_SECONDS))).map(property -> { int gcGraceSeconds = Integer.parseInt(property); return updateAllGCGraceSeconds(gcGraceSeconds); })); } check.subscribe(() -> { stopwatch.stop(); logger.info("Finished gc_grace_seconds updates in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms"); updatesFinished.ifPresent(subject -> subject.onNext(null)); }, t -> { logger.warn("There was an error checking and updating gc_grace_seconds"); updatesFinished.ifPresent(subject -> subject.onNext(t)); }); }
From source file:org.opendaylight.controller.cluster.datastore.MemberNode.java
public void waitForMemberDown(String member) { Stopwatch sw = Stopwatch.createStarted(); while (sw.elapsed(TimeUnit.SECONDS) <= 10) { CurrentClusterState state = Cluster.get(kit.getSystem()).state(); for (Member m : state.getUnreachable()) { if (member.equals(m.getRoles().iterator().next())) { return; }/*from w w w .ja v a 2s . co m*/ } for (Member m : state.getMembers()) { if (m.status() != MemberStatus.up() && member.equals(m.getRoles().iterator().next())) { return; } } Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } fail("Member " + member + " is now down"); }
From source file:com.android.build.gradle.shrinker.FullRunShrinker.java
/** * Performs the full shrinking run. This clears previous incremental state, creates a new * {@link ShrinkerGraph} and fills it with data read from the platform JARs as well as input * classes. Then we find "entry points" that match {@code -keep} rules from the config file, * and walk the graph, setting the counters and finding reachable classes and members. In the * last step we rewrite all reachable class files to only contain kept class members and put * them in the matching output directories. *///from w w w.ja v a2 s. c om public void run(@NonNull Collection<TransformInput> inputs, @NonNull Collection<TransformInput> referencedClasses, @NonNull TransformOutputProvider output, @NonNull ImmutableMap<CounterSet, KeepRules> keepRules, boolean saveState) throws IOException { output.deleteAll(); buildGraph(inputs, referencedClasses); Stopwatch stopwatch = Stopwatch.createStarted(); setCounters(keepRules); logTime("Set counters", stopwatch); writeOutput(inputs, output); logTime("Write output", stopwatch); if (saveState) { mGraph.saveState(); logTime("Saving state", stopwatch); } }
From source file:tds.dll.common.diagnostic.services.impl.DiagnosticDatabaseServiceImpl.java
private DatabaseOperation writeOperation(LegacyDbNameUtility.Databases dbName) { Stopwatch stopwatch = Stopwatch.createStarted(); try {/*from w w w . j a v a 2s.c o m*/ switch (dbName) { case Archive: writeTestDao.writeArchiveDatabase(); break; case Config: writeTestDao.writeConfigsDatabase(); break; case Itembank: writeTestDao.writeItemBankDatabase(); break; case Session: writeTestDao.writeSessionDatabase(); break; } } catch (DiagnosticException diagnosticException) { stopwatch.stop(); return new DatabaseOperation(Rating.FAILED, DatabaseOperationType.WRITE, stopwatch.elapsed(TimeUnit.MILLISECONDS), diagnosticException.getMessage()); } return new DatabaseOperation(Rating.IDEAL, DatabaseOperationType.WRITE, stopwatch.elapsed(TimeUnit.MILLISECONDS)); }
From source file:org.bitcoinj.params.AbstractBitcoinNetParams.java
@Override public void checkDifficultyTransitions(final StoredBlock storedPrev, final Block nextBlock, final BlockStore blockStore) throws VerificationException, BlockStoreException { final Block prev = storedPrev.getHeader(); // Is this supposed to be a difficulty transition point? if (!isDifficultyTransitionPoint(storedPrev.getHeight())) { // No ... so check the difficulty didn't actually change. if (nextBlock.getDifficultyTarget() != prev.getDifficultyTarget()) throw new VerificationException("Unexpected change in difficulty at height " + storedPrev.getHeight() + ": " + Long.toHexString(nextBlock.getDifficultyTarget()) + " vs " + Long.toHexString(prev.getDifficultyTarget())); return;/*from www. jav a 2 s .co m*/ } // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every // two weeks after the initial block chain download. final Stopwatch watch = Stopwatch.createStarted(); Sha256Hash hash = prev.getHash(); StoredBlock cursor = null; final int interval = this.getInterval(); for (int i = 0; i < interval; i++) { cursor = blockStore.get(hash); if (cursor == null) { // This should never happen. If it does, it means we are following an incorrect or busted chain. throw new VerificationException( "Difficulty transition point but we did not find a way back to the last transition point. Not found: " + hash); } hash = cursor.getHeader().getPrevBlockHash(); } checkState(cursor != null && isDifficultyTransitionPoint(cursor.getHeight() - 1), "Didn't arrive at a transition point."); watch.stop(); if (watch.elapsed(TimeUnit.MILLISECONDS) > 50) log.info("Difficulty transition traversal took {}", watch); Block blockIntervalAgo = cursor.getHeader(); int timespan = (int) (prev.getTimeSeconds() - blockIntervalAgo.getTimeSeconds()); // Limit the adjustment step. final int targetTimespan = this.getTargetTimespan(); if (timespan < targetTimespan / 4) timespan = targetTimespan / 4; if (timespan > targetTimespan * 4) timespan = targetTimespan * 4; BigInteger newTarget = Utils.decodeCompactBits(prev.getDifficultyTarget()); newTarget = newTarget.multiply(BigInteger.valueOf(timespan)); newTarget = newTarget.divide(BigInteger.valueOf(targetTimespan)); if (newTarget.compareTo(this.getMaxTarget()) > 0) { log.info("Difficulty hit proof of work limit: {}", newTarget.toString(16)); newTarget = this.getMaxTarget(); } int accuracyBytes = (int) (nextBlock.getDifficultyTarget() >>> 24) - 3; long receivedTargetCompact = nextBlock.getDifficultyTarget(); // The calculated difficulty is to a higher precision than received, so reduce here. BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8); newTarget = newTarget.and(mask); long newTargetCompact = Utils.encodeCompactBits(newTarget); if (newTargetCompact != receivedTargetCompact) throw new VerificationException("Network provided difficulty bits do not match what was calculated: " + Long.toHexString(newTargetCompact) + " vs " + Long.toHexString(receivedTargetCompact)); }
From source file:fi.helsinki.moodi.service.importing.EnrollmentExecutor.java
@Async("taskExecutor") public void processEnrollments(final Course course, final OodiCourseUnitRealisation courseUnitRealisation, final long moodleCourseId) { try {/*from ww w . ja v a 2 s. c o m*/ logger.info("Enrollment executor started for realisationId {} ", course.realisationId); final Stopwatch stopwatch = Stopwatch.createStarted(); final List<EnrollmentWarning> enrollmentWarnings = newArrayList(); final List<Enrollment> enrollments = createEnrollments(courseUnitRealisation); final List<Enrollment> approvedEnrollments = filterApprovedEnrollments(enrollments, enrollmentWarnings); final List<Enrollment> enrollmentsWithUsernames = enrichEnrollmentsWithUsernames(approvedEnrollments); final List<Enrollment> enrollmentsWithMoodleIds = enrichEnrollmentsWithMoodleIds( enrollmentsWithUsernames); batchProcessor.process(enrollmentsWithMoodleIds, itemsToProcess -> persistMoodleEnrollments(moodleCourseId, itemsToProcess, enrollmentWarnings), ENROLLMENT_BATCH_MAX_SIZE); courseService.completeCourseImport(course.realisationId, true); loggingService.logCourseImportEnrollments(course, enrollmentsWithMoodleIds, enrollmentWarnings); logger.info("Enrollment executor for realisationId {} finished in {}", course.realisationId, stopwatch.stop().toString()); } catch (Exception e) { courseService.completeCourseImport(course.realisationId, false); logger.error("Enrollment execution failed for course " + course.realisationId); e.printStackTrace(); } }
From source file:com.android.build.gradle.shrinker.IncrementalShrinker.java
/** * Perform incremental shrinking, in the supported cases (where only code in pre-existing * methods has been modified)./*from w w w. j a v a 2 s. c o m*/ * * <p>The general idea is this: for every method in modified classes, remove all outgoing * "code reference" edges, add them again based on the current code and then set the counters * again (traverse the graph) using the new set of edges. * * <p>The counters are re-calculated every time from scratch (starting from known entry points * from the config file) to avoid cycles being left in the output. * * @throws IncrementalRunImpossibleException If incremental shrinking is impossible and a full * run should be done instead. */ public void incrementalRun(@NonNull Iterable<TransformInput> inputs, @NonNull TransformOutputProvider output) throws IOException, IncrementalRunImpossibleException { final Set<T> classesToWrite = Sets.newConcurrentHashSet(); final Set<File> classFilesToDelete = Sets.newConcurrentHashSet(); final Set<PostProcessingData.UnresolvedReference<T>> unresolvedReferences = Sets.newConcurrentHashSet(); Stopwatch stopwatch = Stopwatch.createStarted(); SetMultimap<T, String> oldState = resetState(); logTime("resetState()", stopwatch); processInputs(inputs, classesToWrite, unresolvedReferences); logTime("processInputs", stopwatch); finishGraph(unresolvedReferences); logTime("finish graph", stopwatch); setCounters(CounterSet.SHRINK); logTime("set counters", stopwatch); chooseClassesToWrite(inputs, output, classesToWrite, classFilesToDelete, oldState); logTime("choose classes", stopwatch); updateClassFiles(classesToWrite, classFilesToDelete, inputs, output); logTime("update class files", stopwatch); mGraph.saveState(); logTime("save state", stopwatch); }
From source file:com.minestellar.moon.MinestellarMoon.java
@EventHandler public void init(FMLInitializationEvent event) { Stopwatch stopwatch = Stopwatch.createStarted(); RecipeManagerMoon.loadRecipes();/* w ww .ja v a2s . com*/ this.registerTileEntities(); this.registerCreatures(); this.registerOtherEntities(); MinestellarMoon.proxy.init(event); log.info("Initialization Completed in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms."); }
From source file:com.b2international.snowowl.snomed.reasoner.server.normalform.ConceptConcreteDomainNormalFormGenerator.java
public void collectNormalFormChanges(final IProgressMonitor monitor, final OntologyChangeProcessor<ConcreteDomainFragment> processor) { LOGGER.info(">>> Concept concrete domain entry normal form generation"); final Stopwatch stopwatch = Stopwatch.createStarted(); collectNormalFormChanges(monitor, processor, ConcreteDomainChangeOrdering.INSTANCE); LOGGER.info(MessageFormat.format("<<< Concept concrete domain entry normal form generation [{0}]", stopwatch.toString()));// w ww. jav a 2s. c o m }