com.facebook.infer.annotation.ThreadSafe Java Examples

The following examples show how to use com.facebook.infer.annotation.ThreadSafe. 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: CompositeMetricsCollector.java    From Battery-Metrics with MIT License 6 votes vote down vote up
/**
 * Gets the snapshot for all the metrics and returns a CompositeMetrics object with the value.
 *
 * <p>Snapshots are only taken of metrics requested in the composite metrics objects; any
 * snapshots that fail or are not supported by this collector are marked invalid. The underlying
 * collectors are expected to report any errors they might encounter.
 *
 * @param snapshot snapshot to reuse
 * @return whether _any_ underlying snapshot succeeded
 */
@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(CompositeMetrics snapshot) {
  checkNotNull(snapshot, "Null value passed to getSnapshot!");
  boolean result = false;
  SimpleArrayMap<Class<? extends SystemMetrics>, SystemMetrics> snapshotMetrics =
      snapshot.getMetrics();
  for (int i = 0, size = snapshotMetrics.size(); i < size; i++) {
    Class<? extends SystemMetrics> metricsClass = snapshotMetrics.keyAt(i);
    SystemMetricsCollector collector = mMetricsCollectorMap.get(metricsClass);
    boolean snapshotResult = false;
    if (collector != null) {
      SystemMetrics metric = snapshot.getMetric(metricsClass);
      snapshotResult = collector.getSnapshot(metric);
    }
    snapshot.setIsValid(metricsClass, snapshotResult);
    result |= snapshotResult;
  }

  return result;
}
 
Example #2
Source File: DeviceBatteryMetricsCollector.java    From Battery-Metrics with MIT License 6 votes vote down vote up
@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(DeviceBatteryMetrics snapshot) {
  checkNotNull(snapshot, "Null value passed to getSnapshot!");
  snapshot.batteryLevelPct = getBatteryLevel(getBatteryIntent());
  long now = SystemClock.elapsedRealtime();
  synchronized (this) {
    if (mIsCurrentlyCharging) {
      snapshot.chargingRealtimeMs = mChargingRealtimeMs + (now - mLastUpdateMs);
      snapshot.batteryRealtimeMs = mBatteryRealtimeMs;
    } else {
      snapshot.chargingRealtimeMs = mChargingRealtimeMs;
      snapshot.batteryRealtimeMs = mBatteryRealtimeMs + (now - mLastUpdateMs);
    }
    return true;
  }
}
 
Example #3
Source File: ComponentLifecycle.java    From litho with Apache License 2.0 6 votes vote down vote up
@ThreadSafe(enableChecks = false)
public Object createMountContent(Context c) {
  final boolean isTracing = ComponentsSystrace.isTracing();
  if (isTracing) {
    ComponentsSystrace.beginSection("createMountContent:" + ((Component) this).getSimpleName());
  }
  try {
    if (ComponentsConfiguration.isGlobalComponentsPoolEnabled && shouldUseGlobalPool()) {
      c = c.getApplicationContext();
    }
    return onCreateMountContent(c);
  } finally {
    if (isTracing) {
      ComponentsSystrace.endSection();
    }
  }
}
 
Example #4
Source File: ComponentLifecycle.java    From litho with Apache License 2.0 6 votes vote down vote up
@ThreadSafe(enableChecks = false)
Component createComponentLayout(ComponentContext c) {
  Component layoutComponent = null;

  try {
    if (Component.isLayoutSpecWithSizeSpec(((Component) this))) {
      layoutComponent = onCreateLayoutWithSizeSpec(c, c.getWidthSpec(), c.getHeightSpec());
    } else {
      layoutComponent = onCreateLayout(c);
    }
  } catch (Exception e) {
    dispatchErrorEvent(c, e);
  }

  return layoutComponent;
}
 
Example #5
Source File: NetworkMetricsCollector.java    From Battery-Metrics with MIT License 6 votes vote down vote up
@Override
@ThreadSafe(enableChecks = false)
public synchronized boolean getSnapshot(NetworkMetrics snapshot) {
  // Once the value has decreased, the underlying value has almost certainly reset and all current
  // snapshots are invalidated. Disable this collector.
  if (!mIsValid || !mCollector.getTotalBytes(mBytes)) {
    return false;
  }

  mIsValid = ensureBytesIncreased(mBytes, mPrevBytes);
  if (!mIsValid) {
    return false;
  }

  boolean supportsBgDetection = mCollector.supportsBgDistinction();
  resetMetrics(snapshot);
  addMetricsFromBytes(snapshot, mBytes, FG);
  if (supportsBgDetection) {
    addMetricsFromBytes(snapshot, mBytes, BG);
  }

  return true;
}
 
Example #6
Source File: EnhancedNetworkMetricsCollector.java    From Battery-Metrics with MIT License 6 votes vote down vote up
@Override
@ThreadSafe(enableChecks = false)
public synchronized boolean getSnapshot(EnhancedNetworkMetrics snapshot) {
  if (!mIsValid || !mCollector.getTotalBytes(mBytes)) {
    return false;
  }

  mIsValid = NetworkMetricsCollector.ensureBytesIncreased(mBytes, mPrevBytes);
  if (!mIsValid) {
    return false;
  }

  boolean supportsBgDetection = mCollector.supportsBgDistinction();
  snapshot.supportsBgDetection = supportsBgDetection;
  NetworkMetricsCollector.resetMetrics(snapshot.fgMetrics);
  NetworkMetricsCollector.addMetricsFromBytes(snapshot.fgMetrics, mBytes, FG);
  if (supportsBgDetection) {
    NetworkMetricsCollector.resetMetrics(snapshot.bgMetrics);
    NetworkMetricsCollector.addMetricsFromBytes(snapshot.bgMetrics, mBytes, BG);
  }

  return true;
}
 
Example #7
Source File: RadioStateCollector.java    From Battery-Metrics with MIT License 6 votes vote down vote up
@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(RadioStateMetrics snapshot) {

  final long mobileNextIdleTimeActive = mMobileRadioMonitor.mNextIdleTimeActive.get();
  snapshot.mobileHighPowerActiveS = MonotonicRadioMonitor.totalTxS(mobileNextIdleTimeActive);
  snapshot.mobileLowPowerActiveS = MonotonicRadioMonitor.totalTailS(mobileNextIdleTimeActive);
  snapshot.mobileRadioWakeupCount = mMobileRadioMonitor.mWakeupCounter.get();

  final long wifiNextIdleTimeActive = mWifiRadioMonitor.mNextIdleTimeActive.get();
  snapshot.wifiActiveS =
      MonotonicRadioMonitor.totalTxS(wifiNextIdleTimeActive)
          + MonotonicRadioMonitor.totalTailS(wifiNextIdleTimeActive);
  snapshot.wifiRadioWakeupCount = mWifiRadioMonitor.mWakeupCounter.get();

  return true;
}
 
Example #8
Source File: BitmapCounterProvider.java    From fresco with MIT License 5 votes vote down vote up
@ThreadSafe
public static BitmapCounter get() {
  if (sBitmapCounter == null) {
    synchronized (BitmapCounterProvider.class) {
      if (sBitmapCounter == null) {
        sBitmapCounter = new BitmapCounter(sMaxBitmapCount, MAX_BITMAP_TOTAL_SIZE);
      }
    }
  }
  return sBitmapCounter;
}
 
Example #9
Source File: TreeProps.java    From litho with Apache License 2.0 5 votes vote down vote up
/** @return a copy of the provided TreeProps instance; returns null if source is null */
@ThreadSafe(enableChecks = false)
public static @Nullable TreeProps copy(@Nullable TreeProps source) {
  if (source == null) {
    return null;
  }

  return acquire(source);
}
 
Example #10
Source File: TimeMetricsCollector.java    From Battery-Metrics with MIT License 5 votes vote down vote up
@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(TimeMetrics snapshot) {
  checkNotNull(snapshot, "Null value passed to getSnapshot!");
  snapshot.realtimeMs = SystemClock.elapsedRealtime();
  snapshot.uptimeMs = SystemClock.uptimeMillis();
  return true;
}
 
Example #11
Source File: AppWakeupMetricsCollector.java    From Battery-Metrics with MIT License 5 votes vote down vote up
@Override
@ThreadSafe(enableChecks = false)
public synchronized boolean getSnapshot(AppWakeupMetrics snapshot) {
  checkNotNull(snapshot, "Null value passed to getSnapshot!");
  // TODO: Optimize by taking intersection of the two lists
  snapshot.appWakeups.clear();
  for (int i = 0; i < mMetrics.appWakeups.size(); i++) {
    WakeupDetails details = new WakeupDetails();
    details.set(mMetrics.appWakeups.valueAt(i));
    snapshot.appWakeups.put(mMetrics.appWakeups.keyAt(i), details);
  }
  return true;
}
 
Example #12
Source File: CpuFrequencyMetricsCollector.java    From Battery-Metrics with MIT License 5 votes vote down vote up
@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(CpuFrequencyMetrics snapshot) {
  checkNotNull(snapshot, "Null value passed to getSnapshot!");
  boolean hasAnyValid = false;
  for (int i = 0, cores = getTotalCores(); i < cores; i++) {
    hasAnyValid |= readCoreStats(snapshot.timeInStateS[i], getReader(i));
  }

  return hasAnyValid;
}
 
Example #13
Source File: MemoryMetricsCollector.java    From Battery-Metrics with MIT License 5 votes vote down vote up
@Override
@ThreadSafe(enableChecks = false)
public synchronized boolean getSnapshot(MemoryMetrics snapshot) {
  checkNotNull(snapshot, "Null value passed to getSnapshot!");
  if (!mIsEnabled) {
    return false;
  }

  /* this helps to track the latest snapshot, diff/sum always picks latest as truth */
  snapshot.sequenceNumber = mCounter.incrementAndGet();

  snapshot.javaHeapMaxSizeKb = getRuntimeMaxMemory() / KB;
  snapshot.javaHeapAllocatedKb = (getRuntimeTotalMemory() - getRuntimeFreeMemory()) / KB;

  snapshot.nativeHeapSizeKb = Debug.getNativeHeapSize() / KB;
  snapshot.nativeHeapAllocatedKb = Debug.getNativeHeapAllocatedSize() / KB;

  snapshot.vmSizeKb = -1;
  snapshot.vmRssKb = -1;

  try {
    ProcFileReader reader = mProcFileReader.get();
    if (reader == null) {
      reader = new ProcFileReader(getPath());
      mProcFileReader.set(reader);
    }

    reader.reset();

    if (reader.isValid()) {
      snapshot.vmSizeKb = readField(reader);
      snapshot.vmRssKb = readField(reader);
    }
  } catch (ProcFileReader.ParseException pe) {
    SystemMetricsLogger.wtf(TAG, "Unable to parse memory (statm) field", pe);
  }

  return true;
}
 
Example #14
Source File: ComponentTree.java    From litho with Apache License 2.0 5 votes vote down vote up
/**
 * Pre-allocate the mount content of all MountSpec in this tree. Must be called after layout is
 * created.
 */
@ThreadSafe(enableChecks = false)
private void preAllocateMountContent(boolean shouldPreallocatePerMountSpec) {
  final LayoutState toPrePopulate;

  synchronized (this) {
    if (mMainThreadLayoutState != null) {
      toPrePopulate = mMainThreadLayoutState;
    } else if (mCommittedLayoutState != null) {
      toPrePopulate = mCommittedLayoutState;
    } else {
      return;
    }
  }
  final ComponentsLogger logger = getContextLogger();
  final PerfEvent event =
      logger != null
          ? LogTreePopulator.populatePerfEventFromLogger(
              mContext,
              logger,
              logger.newPerformanceEvent(mContext, EVENT_PRE_ALLOCATE_MOUNT_CONTENT))
          : null;

  toPrePopulate.preAllocateMountContent(shouldPreallocatePerMountSpec, mRecyclingMode);

  if (event != null) {
    logger.logPerfEvent(event);
  }
}
 
Example #15
Source File: LayoutState.java    From litho with Apache License 2.0 5 votes vote down vote up
@ThreadSafe(enableChecks = false)
void preAllocateMountContent(boolean shouldPreallocatePerMountSpec, int recyclingMode) {
  final boolean isTracing = ComponentsSystrace.isTracing();
  if (isTracing) {
    ComponentsSystrace.beginSection("preAllocateMountContent:" + mComponent.getSimpleName());
  }

  if (mMountableOutputs != null && !mMountableOutputs.isEmpty()) {
    for (int i = 0, size = mMountableOutputs.size(); i < size; i++) {
      final RenderTreeNode treeNode = mMountableOutputs.get(i);
      final LayoutOutput output = LayoutOutput.getLayoutOutput(treeNode);
      final Component component = output.getComponent();

      if (shouldPreallocatePerMountSpec && !component.canPreallocate()) {
        continue;
      }

      if (Component.isMountViewSpec(component)) {
        if (isTracing) {
          ComponentsSystrace.beginSection("preAllocateMountContent:" + component.getSimpleName());
        }

        ComponentsPools.maybePreallocateContent(
            mContext.getAndroidContext(), component, recyclingMode);

        if (isTracing) {
          ComponentsSystrace.endSection();
        }
      }
    }
  }

  if (isTracing) {
    ComponentsSystrace.endSection();
  }
}
 
Example #16
Source File: TreeProps.java    From litho with Apache License 2.0 5 votes vote down vote up
/**
 * Whenever a Spec sets tree props, the TreeProps map from the parent is copied. If parent
 * TreeProps are null, a new TreeProps instance is created to copy the current tree props.
 *
 * <p>Infer knows that newProps is owned but doesn't know that newProps.mMap is owned.
 */
@ThreadSafe(enableChecks = false)
public static TreeProps acquire(TreeProps source) {
  final TreeProps newProps = new TreeProps();
  if (source != null) {
    synchronized (source.mMap) {
      newProps.mMap.putAll(source.mMap);
    }
  }

  return newProps;
}
 
Example #17
Source File: ComponentLifecycle.java    From litho with Apache License 2.0 4 votes vote down vote up
@ThreadSafe
protected int poolSize() {
  return DEFAULT_MAX_PREALLOCATION;
}
 
Example #18
Source File: Transition.java    From litho with Apache License 2.0 4 votes vote down vote up
/** Creates a set of {@link Transition}s that will run in parallel. */
@ThreadSafe(enableChecks = false)
public static <T extends Transition> TransitionSet parallel(T... transitions) {
  return new ParallelTransitionSet(transitions);
}
 
Example #19
Source File: CpuMetricsCollector.java    From Battery-Metrics with MIT License 4 votes vote down vote up
@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(CpuMetrics snapshot) {
  checkNotNull(snapshot, "Null value passed to getSnapshot!");

  try {
    ProcFileReader reader = mProcFileReader.get();
    if (reader == null) {
      reader = new ProcFileReader(getPath());
      mProcFileReader.set(reader);
    }

    reader.reset();

    if (!reader.isValid()) {
      return false;
    }

    int index = 0;
    while (index < PROC_USER_TIME_FIELD) {
      reader.skipSpaces();
      index++;
    }

    snapshot.userTimeS = readField(reader);
    snapshot.systemTimeS = readField(reader);
    snapshot.childUserTimeS = readField(reader);
    snapshot.childSystemTimeS = readField(reader);
  } catch (ProcFileReader.ParseException pe) {
    SystemMetricsLogger.wtf(TAG, "Unable to parse CPU time field", pe);
    return false;
  }

  if (mLastSnapshot.get() == null) {
    mLastSnapshot.set(new CpuMetrics());
  }

  CpuMetrics lastSnapshot = mLastSnapshot.get();
  if (Double.compare(snapshot.userTimeS, lastSnapshot.userTimeS) < 0
      || Double.compare(snapshot.systemTimeS, lastSnapshot.systemTimeS) < 0
      || Double.compare(snapshot.childUserTimeS, lastSnapshot.childUserTimeS) < 0
      || Double.compare(snapshot.childSystemTimeS, lastSnapshot.childSystemTimeS) < 0) {
    SystemMetricsLogger.wtf(
        TAG, "Cpu Time Decreased from " + lastSnapshot.toString() + " to " + snapshot.toString());
    return false;
  }

  lastSnapshot.set(snapshot);
  return true;
}
 
Example #20
Source File: Output.java    From litho with Apache License 2.0 4 votes vote down vote up
/** Assumed thread-safe because the one write is before all the reads */
@ThreadSafe(enableChecks = false)
public void set(@Nullable T t) {
  mT = t;
}
 
Example #21
Source File: Component.java    From litho with Apache License 2.0 4 votes vote down vote up
/**
 * Set a key for this component that is unique within its tree.
 *
 * @param key
 */
// thread-safe because the one write is before all the reads
@ThreadSafe(enableChecks = false)
void setGlobalKey(String key) {
  mGlobalKey = key;
}
 
Example #22
Source File: DiskMetricsCollector.java    From Battery-Metrics with MIT License 4 votes vote down vote up
@Override
@ThreadSafe(enableChecks = false)
public synchronized boolean getSnapshot(DiskMetrics snapshot) {
  checkNotNull(snapshot, "Null value passed to getSnapshot!");
  if (!mIsEnabled) {
    return false;
  }

  try {
    ProcFileReader ioReader = mProcIoFileReader.get();
    if (ioReader == null) {
      ioReader = new ProcFileReader(getIoFilePath());
      mProcIoFileReader.set(ioReader);
    }

    ioReader.reset();

    if (!ioReader.isValid()) {
      return false;
    }

    snapshot.rcharBytes = readField(ioReader);
    snapshot.wcharBytes = readField(ioReader);
    snapshot.syscrCount = readField(ioReader);
    snapshot.syscwCount = readField(ioReader);
    snapshot.readBytes = readField(ioReader);
    snapshot.writeBytes = readField(ioReader);
    snapshot.cancelledWriteBytes = readField(ioReader);

    ProcFileReader statReader = mProcStatFileReader.get();
    if (statReader == null) {
      statReader = new ProcFileReader(getStatFilePath());
      mProcStatFileReader.set(statReader);
    }

    statReader.reset();

    if (!statReader.isValid()) {
      return false;
    }

    int index = 0;
    while (index < PROC_STAT_MAJOR_FAULTS_FIELD) {
      statReader.skipSpaces();
      index++;
    }

    snapshot.majorFaults = statReader.readNumber();

    while (index < PROC_STAT_BLKIO_TICKS_FIELD) {
      statReader.skipSpaces();
      index++;
    }

    snapshot.blkIoTicks = statReader.readNumber();
  } catch (ProcFileReader.ParseException pe) {
    SystemMetricsLogger.wtf(TAG, "Unable to parse disk field", pe);
    return false;
  }

  return true;
}
 
Example #23
Source File: Hierarcher.java    From fresco with MIT License 2 votes vote down vote up
/**
 * Build the actual image wrapper, a forwarding drawable that will forward to the actual image
 * drawable once set and can perform transformations, like scaling.
 *
 * @param imageOptions image options to be used to create the wrapper
 * @return the actual image wrapper drawable
 */
@ThreadSafe
ForwardingDrawable buildActualImageWrapper(ImageOptions imageOptions);