List of usage examples for com.google.common.base Stopwatch createUnstarted
@CheckReturnValue public static Stopwatch createUnstarted()
From source file:org.datacleaner.panels.result.ProgressInformationPanel.java
public ProgressInformationPanel(boolean running) { super(WidgetUtils.COLOR_DEFAULT_BACKGROUND); setLayout(new BorderLayout()); _tableProgressInformationPanels = new ConcurrentHashMap<>(); _progressTimingCounters = new ConcurrentHashMap<>(); _stopWatch = Stopwatch.createUnstarted(); _executionLogTextArea = new JTextArea(); _executionLogTextArea.setText("--- DataCleaner progress information user-log ---"); _executionLogTextArea.setEditable(false); _executionLogTextArea.setBackground(WidgetUtils.COLOR_DEFAULT_BACKGROUND); _progressBarPanel = new DCPanel(WidgetUtils.COLOR_ALTERNATIVE_BACKGROUND); _progressBarPanel.setLayout(new VerticalLayout(4)); final JXTaskPane progressTaskPane = WidgetFactory.createTaskPane("Progress", IconUtils.ACTION_EXECUTE); progressTaskPane.add(_progressBarPanel); final JXTaskPane executionLogTaskPane = WidgetFactory.createTaskPane("Execution log", IconUtils.ACTION_LOG); executionLogTaskPane.add(_executionLogTextArea); final DCTaskPaneContainer taskPaneContainer = WidgetFactory.createTaskPaneContainer(); if (running) { taskPaneContainer.add(progressTaskPane); }/*from w w w .j a va 2 s .c om*/ taskPaneContainer.add(executionLogTaskPane); add(WidgetUtils.scrolleable(taskPaneContainer), BorderLayout.CENTER); }
From source file:org.glowroot.jvm.LazyPlatformMBeanServer.java
@EnsuresNonNull("mbeanServer") private void ensureInit() throws InterruptedException { if (mbeanServer == null) { if (jbossModules) { // if running under jboss-modules, wait it to set up JUL before calling // getPlatformMBeanServer() waitForJBossModuleInitialization(Stopwatch.createUnstarted()); }/*from w w w. j a v a 2s . co m*/ mbeanServer = ManagementFactory.getPlatformMBeanServer(); } }
From source file:io.cloudex.framework.components.Processor.java
@Override public void run() throws IOException { String status = null;/* www . ja va 2 s . c o m*/ Stopwatch stopwatch = Stopwatch.createUnstarted(); VmMetaData metaData = this.getMetaData(); CloudService cloudService = this.getCloudService(); while (true) { try { // only process tasks if the status is empty if (StringUtils.isBlank(status)) { // set status to BUSY metaData.setProcessorStatus(ProcessorStatus.BUSY); cloudService.updateMetadata(metaData); // run the task Task task = taskFactory.getTask(metaData, cloudService); if (task != null) { stopwatch.start(); log.info("Starting processor task: " + task); task.run(); log.info("TIMER# Task " + task + " completed in: " + stopwatch); stopwatch.reset(); } else { //no task is set, just set status to ready and wait for tasks log.info("No task is set!"); } // finished processing // blank the task type and set the status to READY metaData.clearValues(); metaData.setProcessorStatus(ProcessorStatus.READY); cloudService.updateMetadata(metaData); } else { log.info("will continue waiting for instructions as status is currently: " + status); } // now wait for any change in the metadata log.info("Waiting for new instructions from the Coordinator"); // FIXME better solution for race condition // avoid race condition ApiUtils.block(2); metaData = cloudService.getMetaData(false); // if we still have a status then wait, otherwise proceed if (StringUtils.isNotBlank(metaData.getStatus())) { metaData = cloudService.getMetaData(true); } // check the status in the metadata status = metaData.getStatus(); } catch (Exception e) { log.error("An error has occurred whilst running/waiting for tasks, setting status to ERROR", e); // the stopwatch wasn't stopped when an exception was thrown stopwatch.reset(); // try to update the Metadata to a fail status try { metaData = cloudService.getMetaData(false); // blank the task type and set the status to ERROR metaData.clearValues(); metaData.exceptionToCloudExError(e); cloudService.updateMetadata(metaData); // wait until we get further instructions // now wait for any change in the metadata log.info("Waiting for new instructions from the Coordinator"); metaData = cloudService.getMetaData(true); status = metaData.getStatus(); } catch (Exception e1) { // all has failed with no hope of recovery, retry a few times then terminate log.fatal("An error has occurred whilst trying to recover", e); // self terminate :-( // FIXME uncomment once testing is thoroughly done //this.service.shutdownInstance(); } } if (this.stop) { break; } } }
From source file:es.usc.citius.composit.core.composition.search.ForwardServiceDiscoverer.java
public ServiceMatchNetwork<E, T> search(Signature<E> signature) { Set<E> availableInputs = new HashSet<E>(signature.getInputs()); Set<E> newOutputs = new HashSet<E>(signature.getInputs()); Set<E> unmatchedOutputs = new HashSet<E>(signature.getOutputs()); Set<Operation<E>> usedServices = new HashSet<Operation<E>>(); Map<Operation<E>, Set<E>> unmatchedInputMap = new HashMap<Operation<E>, Set<E>>(); List<Set<Operation<E>>> leveledOps = new LinkedList<Set<Operation<E>>>(); boolean checkExpectedOutputs = !signature.getOutputs().isEmpty(); boolean stop; Stopwatch timer = Stopwatch.createStarted(); Stopwatch levelTimer = Stopwatch.createUnstarted(); int level = 0; do {/*from w ww. ja v a2 s .c o m*/ HashSet<Operation<E>> candidates = new HashSet<Operation<E>>(); levelTimer.start(); candidates.addAll(discovery.findOperationsConsumingSome(newOutputs)); log.info("(Level {}) {} potential candidates selected in {}", level++, candidates.size(), levelTimer.toString()); // Remove services that cannot be invoked with the available inputs for (Iterator<Operation<E>> it = candidates.iterator(); it.hasNext();) { Operation<E> candidate = it.next(); // Retrieve the unmatched inputs for this operation Set<E> unmatchedInputs = unmatchedInputMap.get(candidate); if (unmatchedInputs == null) { unmatchedInputs = candidate.getSignature().getInputs(); } // Check if the new concepts match some unmatched inputs Set<E> matched = matcher.partialMatch(newOutputs, unmatchedInputs).getTargetElements(); // Don't check invokability if (relaxedMatchCondition) { // Remove only if there is no match at all if (matched.isEmpty()) { it.remove(); } else { boolean isNew = usedServices.add(candidate); if (!isNew) it.remove(); } } else { // Update the unmatchedInputs unmatchedInputs = Sets.newHashSet(Sets.difference(unmatchedInputs, matched)); unmatchedInputMap.put(candidate, unmatchedInputs); // If there are no unmatched inputs, the service is invokable! if (!unmatchedInputs.isEmpty()) { it.remove(); } else { // Invokable operation, check if it was used previously boolean isNew = usedServices.add(candidate); if (!isNew) it.remove(); } } } log.info("\t + [{}] operations selected for this level in {}", candidates.size(), levelTimer.toString()); log.debug("\t\t Candidates: {}", candidates); // Collect the new outputs of the new candidates Set<E> nextOutputs = Operations.outputs(candidates); // Check unmatched outputs Set<E> matchedOutputs = matcher.partialMatch(Sets.union(newOutputs, nextOutputs), unmatchedOutputs) .getTargetElements(); //Set<Resource> matchedOutputs = matcher.matched(newOutputs, unmatchedOutputs); // Update the unmatched outputs unmatchedOutputs = Sets.newHashSet(Sets.difference(unmatchedOutputs, matchedOutputs)); // Update for the next iteration availableInputs.addAll(newOutputs); newOutputs = nextOutputs; // Add the discovered ops if (!candidates.isEmpty()) leveledOps.add(candidates); log.debug("\t + Available inputs: {}, new outputs: {}", availableInputs.size(), newOutputs.size()); // Stop condition. Stop if there are no more candidates and/or expected outputs are satisfied. stop = (checkExpectedOutputs) ? candidates.isEmpty() || unmatchedOutputs.isEmpty() : candidates.isEmpty(); levelTimer.reset(); } while (!stop); // Add the source and sink operations Source<E> sourceOp = new Source<E>(signature.getInputs()); Sink<E> sinkOp = new Sink<E>(signature.getOutputs()); leveledOps.add(0, Collections.<Operation<E>>singleton(sourceOp)); leveledOps.add(leveledOps.size(), Collections.<Operation<E>>singleton(sinkOp)); Stopwatch networkWatch = Stopwatch.createStarted(); // Create a service match network with the discovered services DirectedAcyclicSMN<E, T> matchNetwork = new DirectedAcyclicSMN<E, T>(new HashLeveledServices<E>(leveledOps), this.matcher); log.info(" > Service match network computed in {}", networkWatch.stop().toString()); log.info("Service Match Network created with {} levels (including source and sink) and {} operations.", leveledOps.size(), matchNetwork.listOperations().size()); log.info("Forward Discovery done in {}", timer.toString()); this.unmatchedInputMap = unmatchedInputMap; return matchNetwork; }
From source file:org.lenskit.util.monitor.TrackedJob.java
private TrackedJob(TrackedJob parent, String type, String description) { this.parent = parent; this.type = type; this.description = description; this.eventBus = parent.getEventBus(); this.uuid = UUID.randomUUID(); timer = Stopwatch.createUnstarted(); }
From source file:org.apache.druid.server.coordinator.DruidCoordinatorBalancerProfiler.java
public void bigProfiler() { Stopwatch watch = Stopwatch.createUnstarted(); int numSegments = 55000; int numServers = 50; EasyMock.expect(manager.getAllRules()).andReturn(ImmutableMap.of("test", rules)).anyTimes(); EasyMock.expect(manager.getRules(EasyMock.anyObject())).andReturn(rules).anyTimes(); EasyMock.expect(manager.getRulesWithDefault(EasyMock.anyObject())).andReturn(rules).anyTimes(); EasyMock.replay(manager);//from w w w . j a v a 2s .co m coordinator.moveSegment(EasyMock.anyObject(), EasyMock.anyObject(), EasyMock.anyObject(), EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); EasyMock.replay(coordinator); List<DruidServer> serverList = Lists.newArrayList(); Map<String, LoadQueuePeon> peonMap = Maps.newHashMap(); List<ServerHolder> serverHolderList = Lists.newArrayList(); Map<String, DataSegment> segmentMap = Maps.newHashMap(); for (int i = 0; i < numSegments; i++) { segmentMap.put("segment" + i, new DataSegment("datasource" + i, new Interval(DateTimes.of("2012-01-01"), (DateTimes.of("2012-01-01")).plusHours(1)), (DateTimes.of("2012-03-01")).toString(), Maps.newHashMap(), Lists.newArrayList(), Lists.newArrayList(), NoneShardSpec.instance(), 0, 4L)); } for (int i = 0; i < numServers; i++) { ImmutableDruidServer server = EasyMock.createMock(ImmutableDruidServer.class); EasyMock.expect(server.getMetadata()).andReturn(null).anyTimes(); EasyMock.expect(server.getCurrSize()).andReturn(30L).atLeastOnce(); EasyMock.expect(server.getMaxSize()).andReturn(100L).atLeastOnce(); EasyMock.expect(server.getTier()).andReturn("normal").anyTimes(); EasyMock.expect(server.getName()).andReturn(Integer.toString(i)).atLeastOnce(); EasyMock.expect(server.getHost()).andReturn(Integer.toString(i)).anyTimes(); if (i == 0) { EasyMock.expect(server.getSegments()).andReturn(segmentMap).anyTimes(); } else { EasyMock.expect(server.getSegments()).andReturn(new HashMap<String, DataSegment>()).anyTimes(); } EasyMock.expect(server.getSegment(EasyMock.anyObject())).andReturn(null).anyTimes(); EasyMock.replay(server); LoadQueuePeon peon = new LoadQueuePeonTester(); peonMap.put(Integer.toString(i), peon); serverHolderList.add(new ServerHolder(server, peon)); } DruidCoordinatorRuntimeParams params = DruidCoordinatorRuntimeParams.newBuilder() .withDruidCluster(new DruidCluster(null, ImmutableMap.of("normal", serverHolderList.stream().collect(Collectors.toCollection( () -> new TreeSet<>(DruidCoordinatorBalancer.percentUsedComparator)))))) .withLoadManagementPeons(peonMap).withAvailableSegments(segmentMap.values()) .withDynamicConfigs(CoordinatorDynamicConfig.builder().withMaxSegmentsToMove(MAX_SEGMENTS_TO_MOVE) .withReplicantLifetime(500).withReplicationThrottleLimit(5).build()) .withBalancerReferenceTimestamp(DateTimes.of("2013-01-01")).withEmitter(emitter) .withDatabaseRuleManager(manager).withReplicationManager(new ReplicationThrottler(2, 500)) .withSegmentReplicantLookup( SegmentReplicantLookup.make(new DruidCluster(null, ImmutableMap.of("normal", serverHolderList.stream().collect(Collectors.toCollection( () -> new TreeSet<>(DruidCoordinatorBalancer.percentUsedComparator))))))) .build(); DruidCoordinatorBalancerTester tester = new DruidCoordinatorBalancerTester(coordinator); DruidCoordinatorRuleRunner runner = new DruidCoordinatorRuleRunner(coordinator); watch.start(); DruidCoordinatorRuntimeParams balanceParams = tester.run(params); DruidCoordinatorRuntimeParams assignParams = runner.run(params); System.out.println(watch.stop()); }
From source file:com.google.caliper.runner.worker.WorkerRunner.java
/** * Starts up the worker process and runs it to completion, processing data received from it with * the provided {@link WorkerProcessor}. Returns the result object produced by the processor. *///from ww w . j ava 2 s. c om public R runWorker() { checkState(worker.state() == State.NEW, "You can only invoke the run loop once"); // logger must be opened before starting worker WorkerOutputLogger workerLogger = worker.outputLogger(); try { workerLogger.open(); } catch (IOException e) { throw processor.newWorkerException( String.format("Failed to open output logger for worker [%s].", worker.name()), e); } outputFile = workerLogger.outputFile(); worker.startAsync(); try { workerLogger.printHeader(); long timeLimitNanos = processor.timeLimit().to(NANOSECONDS); Stopwatch stopwatch = Stopwatch.createUnstarted(); worker.awaitRunning(); worker.sendRequest(); stopwatch.start(); while (!done) { Worker.StreamItem item; try { item = worker.readItem(timeLimitNanos - stopwatch.elapsed(NANOSECONDS), NANOSECONDS); } catch (InterruptedException e) { // Someone has asked us to stop (via Futures.cancel?). if (!doneProcessing) { throw processor .newWorkerException(formatError(processor.getInterruptionErrorMessage(worker)), e); } logger.log(Level.WARNING, // Yes, we're doing the formatting eagerly here even though the log level might not // be enabled. It seems like a small sacrifice in this case for more readable code. formatError( "Worker [%s] cancelled before completing normally, but after getting results.", worker)); done = true; break; } switch (item.kind()) { case DATA: doneProcessing = processor.handleMessage(item.content(), worker); if (doneProcessing) { // The worker should be done now; give it WORKER_CLEANUP_DURATION nanos to finish // shutting down. long cleanupTimeNanos = MILLISECONDS.toNanos(WORKER_CLEANUP_DURATION.getMillis()); timeLimitNanos = stopwatch.elapsed(NANOSECONDS) + cleanupTimeNanos; } break; case EOF: // We consider EOF to be synonymous with worker shutdown if (!doneProcessing) { throw processor.newWorkerException( formatError(processor.getPrematureExitErrorMessage(worker)), null); } done = true; break; case TIMEOUT: if (!doneProcessing) { throw processor.newWorkerException(formatError(processor.getTimeoutErrorMessage(worker)), null); } logger.log(Level.WARNING, formatError("Worker [%s] failed to exit cleanly within the allotted time.", worker)); done = true; break; default: throw new AssertionError("Impossible item: " + item); } } return processor.getResult(); } catch (WorkerException e) { throw e; } catch (Throwable e) { logger.severe(formatError("Unexpected error while running worker [%s].", worker)); Throwables.throwIfUnchecked(e); throw new RuntimeException(e); } finally { worker.stopAsync(); try { workerLogger.ensureFileIsSaved(); } finally { workerLogger.close(); } } }
From source file:org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl.java
public BGPSessionStateImpl() { this.sessionState = State.OPEN_CONFIRM; this.sessionStopwatch = Stopwatch.createUnstarted(); }
From source file:nextmethod.web.razor.editor.internal.BackgroundThread.java
private void workerLoop() { final boolean isEditorTracing = Debug.isDebugArgPresent(DebugArgs.EditorTracing); final String fileNameOnly = Filesystem.getFileName(fileName); Stopwatch sw = null;//w w w . j av a2 s . com if (isEditorTracing) { sw = Stopwatch.createUnstarted(); } try { RazorEditorTrace.traceLine(RazorResources().traceBackgroundThreadStart(fileNameOnly)); ensureOnThread(); while (!shutdownToken.isCancellationRequested()) { // Grab the parcel of work to do final WorkParcel parcel = main.getParcel(); if (!parcel.getChanges().isEmpty()) { RazorEditorTrace.traceLine(RazorResources().traceChangesArrived(fileNameOnly, String.valueOf(parcel.getChanges().size()))); try { DocumentParseCompleteEventArgs args = null; try (CancellationTokenSource linkedCancel = CancellationTokenSource .createLinkedTokenSource(shutdownToken, parcel.getCancelToken())) { if (parcel != null && !linkedCancel.isCancellationRequested()) { // Collect ALL changes if (isEditorTracing && previouslyDiscarded != null && !previouslyDiscarded.isEmpty()) { RazorEditorTrace.traceLine(RazorResources().traceCollectedDiscardedChanges( fileNameOnly, String.valueOf(parcel.getChanges().size()))); } final Iterable<TextChange> allChanges = Iterables .concat(previouslyDiscarded != null ? previouslyDiscarded : Collections.<TextChange>emptyList(), parcel.getChanges()); final TextChange finalChange = Iterables.getLast(allChanges, null); if (finalChange != null) { if (isEditorTracing) { assert sw != null; sw.reset().start(); } //noinspection ConstantConditions final GeneratorResults results = parseChange(finalChange.getNewBuffer(), linkedCancel.getToken()); if (isEditorTracing) { assert sw != null; sw.stop(); } RazorEditorTrace.traceLine(RazorResources().traceParseComplete(fileNameOnly, sw != null ? sw.toString() : "?")); if (results != null && !linkedCancel.isCancellationRequested()) { // Clear discarded changes list previouslyDiscarded = Lists.newArrayList(); // Take the current tree and check for differences if (isEditorTracing) { sw.reset().start(); } final boolean treeStructureChanged = currentParseTree == null || BackgroundParser.treesAreDifferent(currentParseTree, results.getDocument(), allChanges, parcel.getCancelToken()); if (isEditorTracing) { sw.stop(); } currentParseTree = results.getDocument(); RazorEditorTrace.traceLine(RazorResources().traceTreesCompared(fileNameOnly, sw != null ? sw.toString() : "?", String.valueOf(treeStructureChanged))); // Build Arguments args = new DocumentParseCompleteEventArgs(treeStructureChanged, results, finalChange); } else { // Parse completed but we were cancelled in the mean time. Add these to the discarded changes set RazorEditorTrace.traceLine(RazorResources().traceChangesDiscarded( fileNameOnly, String.valueOf(Iterables.size(allChanges)))); previouslyDiscarded = Lists.newArrayList(allChanges); } if (Debug.isDebugArgPresent(DebugArgs.CheckTree) && args != null) { // Rewind the buffer and sanity check the line mappings finalChange.getNewBuffer().setPosition(0); final String buffer = TextExtensions.readToEnd(finalChange.getNewBuffer()); final int lineCount = Iterables .size(Splitter.on(CharMatcher.anyOf("\r\n")).split(buffer)); Debug.doAssert(!Iterables.any( args.getGeneratorResults().getDesignTimeLineMappingEntries(), input -> input != null && input.getValue().getStartLine() > lineCount), "Found a design-time line mapping referring to a line outside the source file!"); Debug.doAssert( !Iterables.any(args.getGeneratorResults().getDocument().flatten(), input -> input != null && input.getStart().getLineIndex() > lineCount), "Found a span with a line number outside the source file"); } } } } if (args != null) { main.returnParcel(args); } } catch (OperationCanceledException ignored) { } } else { RazorEditorTrace.traceLine(RazorResources().traceNoChangesArrived(fileName), parcel.getChanges().size()); Thread.yield(); } } } catch (OperationCanceledException ignored) { } finally { RazorEditorTrace.traceLine(RazorResources().traceBackgroundThreadShutdown(fileNameOnly)); // Clean up main thread resources main.close(); } }
From source file:org.eobjects.datacleaner.panels.result.ProgressInformationPanel.java
public ProgressInformationPanel(boolean running) { super();/*from ww w . j a v a 2s.c o m*/ setLayout(new BorderLayout()); _tableProgressInformationPanels = new ConcurrentHashMap<Table, TableProgressInformationPanel>(); _progressTimingCounters = new ConcurrentHashMap<Table, ProgressCounter>(); _stopWatch = Stopwatch.createUnstarted(); _executionLogTextArea = new JTextArea(); _executionLogTextArea.setText("--- DataCleaner progress information user-log ---"); _executionLogTextArea.setEditable(false); _progressBarPanel = new DCPanel(WidgetUtils.BG_COLOR_DARK, WidgetUtils.BG_COLOR_DARK); _progressBarPanel.setLayout(new VerticalLayout(4)); final JXTaskPane progressTaskPane = WidgetFactory.createTaskPane("Progress", ICON_PROGRESS); progressTaskPane.add(_progressBarPanel); final JXTaskPane executionLogTaskPane = WidgetFactory.createTaskPane("Execution log", ICON_EXECUTION_LOG); executionLogTaskPane.add(_executionLogTextArea); _taskPaneContainer = WidgetFactory.createTaskPaneContainer(); if (running) { _taskPaneContainer.add(progressTaskPane); } _taskPaneContainer.add(executionLogTaskPane); add(WidgetUtils.scrolleable(_taskPaneContainer), BorderLayout.CENTER); }