Search code examples
androidperformancefirebasememory-leaksfirebase-performance

How to remove trace started with FirebasePerformance


We want to have a system where there are several types of traces (declared in enum) and we assume that every type of trace will be the one of this type in all the trace's life span. We use something like this:

public class FirebasePerfAnalytics {

  private ConcurrentHashMap<TraceType, Trace> traces = new ConcurrentHashMap<>();

  public Trace startTrace(TraceType traceType) {
    Trace trace = traces.get(traceType);
    if (trace == null) {
      trace = FirebasePerformance.getInstance().newTrace(traceType.name());
      Trace oldTrace = traces.put(traceType, trace);
      if (oldTrace == null) {
        trace.start();
      }
    }
    return trace;
  }

  public void stopTrace(TraceType traceType) {
    Trace trace = traces.remove(traceType);
    if (trace != null) {
      trace.stop();
    }
  }

  public enum TraceType {
   // some types
  }
}

There are cases when a trace will be opened but never closed (because the actual task we want to test is not finished correctly). We don't want to track such error cases but we don't want to leak these small Trace objects.

Is there a way to remove them from the Firebase Performance traces list without calling Trace.stop() method?


Solution

  • Just clear all references to the Trace object and let it get garbage collected. A Trace doesn't really do anything until you call stop() anyway.