Java Code Examples for com.google.common.base.Stopwatch#isRunning()

The following examples show how to use com.google.common.base.Stopwatch#isRunning() . 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: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
ImmutableMap<Service, Long> startupTimes() {
  List<Entry<Service, Long>> loadTimes;
  monitor.enter();
  try {
    loadTimes = Lists.newArrayListWithCapacity(startupTimers.size());
    // N.B. There will only be an entry in the map if the service has started
    for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) {
      Service service = entry.getKey();
      Stopwatch stopWatch = entry.getValue();
      if (!stopWatch.isRunning() && !(service instanceof NoOpService)) {
        loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS)));
      }
    }
  } finally {
    monitor.leave();
  }
  Collections.sort(loadTimes, Ordering.natural().onResultOf(new Function<Entry<Service, Long>, Long>() {
                                                              @Override
                                                              public Long apply(Map.Entry<Service, Long> input) {
                                                                return input.getValue();
                                                              }
                                                            }));
  return ImmutableMap.copyOf(loadTimes);
}
 
Example 2
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
ImmutableMap<Service, Long> startupTimes() {
  List<Entry<Service, Long>> loadTimes;
  monitor.enter();
  try {
    loadTimes = Lists.newArrayListWithCapacity(startupTimers.size());
    // N.B. There will only be an entry in the map if the service has started
    for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) {
      Service service = entry.getKey();
      Stopwatch stopWatch = entry.getValue();
      if (!stopWatch.isRunning() && !(service instanceof NoOpService)) {
        loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS)));
      }
    }
  } finally {
    monitor.leave();
  }
  Collections.sort(loadTimes, Ordering.natural().onResultOf(new Function<Entry<Service, Long>, Long>() {
                                                              @Override
                                                              public Long apply(Map.Entry<Service, Long> input) {
                                                                return input.getValue();
                                                              }
                                                            }));
  return ImmutableMap.copyOf(loadTimes);
}
 
Example 3
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
ImmutableMap<Service, Long> startupTimes() {
  List<Entry<Service, Long>> loadTimes;
  monitor.enter();
  try {
    loadTimes = Lists.newArrayListWithCapacity(startupTimers.size());
    // N.B. There will only be an entry in the map if the service has started
    for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) {
      Service service = entry.getKey();
      Stopwatch stopWatch = entry.getValue();
      if (!stopWatch.isRunning() && !(service instanceof NoOpService)) {
        loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS)));
      }
    }
  } finally {
    monitor.leave();
  }
  Collections.sort(loadTimes, Ordering.natural().onResultOf(new Function<Entry<Service, Long>, Long>() {
                                                              @Override
                                                              public Long apply(Map.Entry<Service, Long> input) {
                                                                return input.getValue();
                                                              }
                                                            }));
  return ImmutableMap.copyOf(loadTimes);
}
 
Example 4
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
ImmutableMap<Service, Long> startupTimes() {
  List<Entry<Service, Long>> loadTimes;
  monitor.enter();
  try {
    loadTimes = Lists.newArrayListWithCapacity(startupTimers.size());
    // N.B. There will only be an entry in the map if the service has started
    for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) {
      Service service = entry.getKey();
      Stopwatch stopWatch = entry.getValue();
      if (!stopWatch.isRunning() && !(service instanceof NoOpService)) {
        loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS)));
      }
    }
  } finally {
    monitor.leave();
  }
  Collections.sort(loadTimes, Ordering.natural().onResultOf(new Function<Entry<Service, Long>, Long>() {
                                                              @Override
                                                              public Long apply(Map.Entry<Service, Long> input) {
                                                                return input.getValue();
                                                              }
                                                            }));
  return ImmutableMap.copyOf(loadTimes);
}
 
Example 5
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
ImmutableMap<Service, Long> startupTimes() {
  List<Entry<Service, Long>> loadTimes;
  monitor.enter();
  try {
    loadTimes = Lists.newArrayListWithCapacity(startupTimers.size());
    // N.B. There will only be an entry in the map if the service has started
    for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) {
      Service service = entry.getKey();
      Stopwatch stopWatch = entry.getValue();
      if (!stopWatch.isRunning() && !(service instanceof NoOpService)) {
        loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS)));
      }
    }
  } finally {
    monitor.leave();
  }
  Collections.sort(
      loadTimes,
      Ordering.natural()
          .onResultOf(
              new Function<Entry<Service, Long>, Long>() {
                @Override
                public Long apply(Map.Entry<Service, Long> input) {
                  return input.getValue();
                }
              }));
  return ImmutableMap.copyOf(loadTimes);
}
 
Example 6
Source File: ModulesSupport.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
/**
 * Search for extensions in guice bindings (directly declared in modules).
 * Only user provided modules are analyzed. Overriding modules are not analyzed.
 * <p>
 * Use guice SPI. In order to avoid duplicate analysis in injector creation time, wrap
 * parsed elements as new module (and use it instead of original modules). Also, if
 * bound extension is disabled, target binding is simply removed (in order to
 * provide the same disable semantic as with usual extensions).
 *
 * @param context configuration context
 * @return list of repackaged modules to use
 */
private static List<Module> analyzeModules(final ConfigurationContext context,
                                           final Stopwatch modulesTimer) {
    List<Module> modules = context.getNormalModules();
    final Boolean configureFromGuice = context.option(AnalyzeGuiceModules);
    // one module mean no user modules registered
    if (modules.size() > 1 && configureFromGuice) {
        // analyzing only user bindings (excluding overrides and guicey technical bindings)
        final GuiceBootstrapModule bootstrap = (GuiceBootstrapModule) modules.remove(modules.size() - 1);
        try {
            // find extensions and remove bindings if required (disabled extensions)
            final Stopwatch gtime = context.stat().timer(Stat.BindingsResolutionTime);
            final List<Element> elements = new ArrayList<>(
                    Elements.getElements(context.option(InjectorStage), modules));
            gtime.stop();

            // exclude analysis time from modules processing time (it's installer time)
            modulesTimer.stop();
            analyzeAndFilterBindings(context, modules, elements);
            modulesTimer.start();

            // wrap raw elements into module to avoid duplicate work on guice startup and put back bootstrap
            modules = Arrays.asList(Elements.getModule(elements), bootstrap);
        } catch (Exception ex) {
            // better show meaningful message then just fail entire startup with ambiguous message
            // NOTE if guice configuration is not OK it will fail here too, but user will see injector creation
            // error as last error in logs.
            LOGGER.error("Failed to analyze guice bindings - skipping this step. Note that configuration"
                    + " from bindings may be switched off with " + GuiceyOptions.class.getSimpleName() + "."
                    + AnalyzeGuiceModules.name() + " option.", ex);
            // recover and use original modules
            modules.add(bootstrap);
            if (!modulesTimer.isRunning()) {
                modulesTimer.start();
            }
        }
    }
    return modules;
}
 
Example 7
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Updates the state with the given service transition.
 *
 * <p>This method performs the main logic of ServiceManager in the following steps.
 * <ol>
 * <li>Update the {@link #servicesByState()}
 * <li>Update the {@link #startupTimers}
 * <li>Based on the new state queue listeners to run
 * <li>Run the listeners (outside of the lock)
 * </ol>
 */

void transitionService(
  final Service service, State from, State to) {
  checkNotNull(service);
  checkArgument(from != to);
  monitor.enter();
  try {
    transitioned = true;
    if (!ready) {
      return;
    }
    // Update state.
    checkState(
      servicesByState.remove(from, service),
      "Service %s not at the expected location in the state map %s",
      service,
      from);
    checkState(
      servicesByState.put(to, service),
      "Service %s in the state map unexpectedly at %s",
      service,
      to);
    // Update the timer
    Stopwatch stopwatch = startupTimers.get(service);
    if (stopwatch == null) {
      // This means the service was started by some means other than ServiceManager.startAsync
      stopwatch = Stopwatch.createStarted();
      startupTimers.put(service, stopwatch);
    }
    if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) {
      // N.B. if we miss the STARTING event then we may never record a startup time.
      stopwatch.stop();
      if (!(service instanceof NoOpService)) {
        logger.log(Level.FINE, "Started {0} in {1}.", new Object[] {service, stopwatch});
      }
    }
    // Queue our listeners

    // Did a service fail?
    if (to == FAILED) {
      fireFailedListeners(service);
    }
    if (states.count(RUNNING) == numberOfServices) {
      // This means that the manager is currently healthy. N.B. If other threads call isHealthy
      // they are not guaranteed to get 'true', because any service could fail right now.
      fireHealthyListeners();
    } else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) {
      fireStoppedListeners();
    }
  } finally {
    monitor.leave();
    // Run our executors outside of the lock
    executeListeners();
  }
}
 
Example 8
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Updates the state with the given service transition.
 *
 * <p>This method performs the main logic of ServiceManager in the following steps.
 * <ol>
 * <li>Update the {@link #servicesByState()}
 * <li>Update the {@link #startupTimers}
 * <li>Based on the new state queue listeners to run
 * <li>Run the listeners (outside of the lock)
 * </ol>
 */

void transitionService(
  final Service service, State from, State to) {
  checkNotNull(service);
  checkArgument(from != to);
  monitor.enter();
  try {
    transitioned = true;
    if (!ready) {
      return;
    }
    // Update state.
    checkState(
      servicesByState.remove(from, service),
      "Service %s not at the expected location in the state map %s",
      service,
      from);
    checkState(
      servicesByState.put(to, service),
      "Service %s in the state map unexpectedly at %s",
      service,
      to);
    // Update the timer
    Stopwatch stopwatch = startupTimers.get(service);
    if (stopwatch == null) {
      // This means the service was started by some means other than ServiceManager.startAsync
      stopwatch = Stopwatch.createStarted();
      startupTimers.put(service, stopwatch);
    }
    if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) {
      // N.B. if we miss the STARTING event then we may never record a startup time.
      stopwatch.stop();
      if (!(service instanceof NoOpService)) {
        logger.log(Level.FINE, "Started {0} in {1}.", new Object[] {service, stopwatch});
      }
    }
    // Queue our listeners

    // Did a service fail?
    if (to == FAILED) {
      fireFailedListeners(service);
    }
    if (states.count(RUNNING) == numberOfServices) {
      // This means that the manager is currently healthy. N.B. If other threads call isHealthy
      // they are not guaranteed to get 'true', because any service could fail right now.
      fireHealthyListeners();
    } else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) {
      fireStoppedListeners();
    }
  } finally {
    monitor.leave();
    // Run our executors outside of the lock
    executeListeners();
  }
}
 
Example 9
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Updates the state with the given service transition.
 *
 * <p>This method performs the main logic of ServiceManager in the following steps.
 * <ol>
 * <li>Update the {@link #servicesByState()}
 * <li>Update the {@link #startupTimers}
 * <li>Based on the new state queue listeners to run
 * <li>Run the listeners (outside of the lock)
 * </ol>
 */

void transitionService(
  final Service service, State from, State to) {
  checkNotNull(service);
  checkArgument(from != to);
  monitor.enter();
  try {
    transitioned = true;
    if (!ready) {
      return;
    }
    // Update state.
    checkState(
      servicesByState.remove(from, service),
      "Service %s not at the expected location in the state map %s",
      service,
      from);
    checkState(
      servicesByState.put(to, service),
      "Service %s in the state map unexpectedly at %s",
      service,
      to);
    // Update the timer
    Stopwatch stopwatch = startupTimers.get(service);
    if (stopwatch == null) {
      // This means the service was started by some means other than ServiceManager.startAsync
      stopwatch = Stopwatch.createStarted();
      startupTimers.put(service, stopwatch);
    }
    if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) {
      // N.B. if we miss the STARTING event then we may never record a startup time.
      stopwatch.stop();
      if (!(service instanceof NoOpService)) {
        logger.log(Level.FINE, "Started {0} in {1}.", new Object[] {service, stopwatch});
      }
    }
    // Queue our listeners

    // Did a service fail?
    if (to == FAILED) {
      fireFailedListeners(service);
    }
    if (states.count(RUNNING) == numberOfServices) {
      // This means that the manager is currently healthy. N.B. If other threads call isHealthy
      // they are not guaranteed to get 'true', because any service could fail right now.
      fireHealthyListeners();
    } else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) {
      fireStoppedListeners();
    }
  } finally {
    monitor.leave();
    // Run our executors outside of the lock
    executeListeners();
  }
}
 
Example 10
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Updates the state with the given service transition.
 *
 * <p>This method performs the main logic of ServiceManager in the following steps.
 * <ol>
 * <li>Update the {@link #servicesByState()}
 * <li>Update the {@link #startupTimers}
 * <li>Based on the new state queue listeners to run
 * <li>Run the listeners (outside of the lock)
 * </ol>
 */

void transitionService(
  final Service service, State from, State to) {
  checkNotNull(service);
  checkArgument(from != to);
  monitor.enter();
  try {
    transitioned = true;
    if (!ready) {
      return;
    }
    // Update state.
    checkState(
      servicesByState.remove(from, service),
      "Service %s not at the expected location in the state map %s",
      service,
      from);
    checkState(
      servicesByState.put(to, service),
      "Service %s in the state map unexpectedly at %s",
      service,
      to);
    // Update the timer
    Stopwatch stopwatch = startupTimers.get(service);
    if (stopwatch == null) {
      // This means the service was started by some means other than ServiceManager.startAsync
      stopwatch = Stopwatch.createStarted();
      startupTimers.put(service, stopwatch);
    }
    if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) {
      // N.B. if we miss the STARTING event then we may never record a startup time.
      stopwatch.stop();
      if (!(service instanceof NoOpService)) {
        logger.log(Level.FINE, "Started {0} in {1}.", new Object[] {service, stopwatch});
      }
    }
    // Queue our listeners

    // Did a service fail?
    if (to == FAILED) {
      fireFailedListeners(service);
    }
    if (states.count(RUNNING) == numberOfServices) {
      // This means that the manager is currently healthy. N.B. If other threads call isHealthy
      // they are not guaranteed to get 'true', because any service could fail right now.
      fireHealthyListeners();
    } else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) {
      fireStoppedListeners();
    }
  } finally {
    monitor.leave();
    // Run our executors outside of the lock
    executeListeners();
  }
}
 
Example 11
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Updates the state with the given service transition.
 *
 * <p>This method performs the main logic of ServiceManager in the following steps.
 * <ol>
 * <li>Update the {@link #servicesByState()}
 * <li>Update the {@link #startupTimers}
 * <li>Based on the new state queue listeners to run
 * <li>Run the listeners (outside of the lock)
 * </ol>
 */
void transitionService(final Service service, State from, State to) {
  checkNotNull(service);
  checkArgument(from != to);
  monitor.enter();
  try {
    transitioned = true;
    if (!ready) {
      return;
    }
    // Update state.
    checkState(
        servicesByState.remove(from, service),
        "Service %s not at the expected location in the state map %s",
        service,
        from);
    checkState(
        servicesByState.put(to, service),
        "Service %s in the state map unexpectedly at %s",
        service,
        to);
    // Update the timer
    Stopwatch stopwatch = startupTimers.get(service);
    if (stopwatch == null) {
      // This means the service was started by some means other than ServiceManager.startAsync
      stopwatch = Stopwatch.createStarted();
      startupTimers.put(service, stopwatch);
    }
    if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) {
      // N.B. if we miss the STARTING event then we may never record a startup time.
      stopwatch.stop();
      if (!(service instanceof NoOpService)) {
        logger.log(Level.FINE, "Started {0} in {1}.", new Object[] {service, stopwatch});
      }
    }
    // Queue our listeners

    // Did a service fail?
    if (to == FAILED) {
      fireFailedListeners(service);
    }

    if (states.count(RUNNING) == numberOfServices) {
      // This means that the manager is currently healthy. N.B. If other threads call isHealthy
      // they are not guaranteed to get 'true', because any service could fail right now.
      fireHealthyListeners();
    } else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) {
      fireStoppedListeners();
    }
  } finally {
    monitor.leave();
    // Run our executors outside of the lock
    executeListeners();
  }
}
 
Example 12
Source File: LoggingFilter.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
  throws IOException {
  if (!"1".equals(requestContext.getHeaderString("Is-Healthcheck"))) {
    //Actual log is done when the response stream has finished in aroundWriteTo
    String log = "< " +
      Integer.toString(responseContext.getStatus()) + " " +
      requestContext.getMethod() + " " +
      requestContext.getUriInfo().getRequestUri().toASCIIString();

    Stopwatch stopwatch = (Stopwatch) requestContext.getProperty(STOPWATCH_PROPERTY);
    if (stopwatch == null) {
      LOG.error("Lost my stopwatch!");
    } else if (!stopwatch.isRunning()) {
      LOG.error("Stopwatch was stopped!");
      stopwatch = null;
    }

    if (responseContext.hasEntity()) {
      String contentType = responseContext.getHeaderString("Content-Type");
      boolean logResponseText = "text/plain".equals(contentType) || "application/json".equals(contentType);
      //delay logging until the responseBody has been fully written
      responseContext.setEntityStream(new LoggingOutputStream(
        responseContext.getEntityStream(),
        stopwatch,
        log,
        requestContext,
        responseContext,
        MDC.getCopyOfContextMap(),
        logResponseText
      ));
    } else {
      //log now, because the writeTo wrapper will not be called
      long duration = stopwatch != null ? stopwatch.elapsed(MILLISECONDS) : -1;
      doLog(
        log,
        0,
        duration,
        duration,
        requestContext,
        responseContext,
        MDC.getCopyOfContextMap(),
        EMPTY
      );
    }
  }
}