com.eg.agent.android.stats.StatisticsEngine Maven / Gradle / Ivy
The newest version!
package com.eg.agent.android.stats;
import com.eg.agent.android.harvest.ReaperAdapter;
import com.eg.agent.android.metric.MetricData;
import com.eg.agent.android.Queue;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
public class StatisticsEngine extends ReaperAdapter {
public static final StatisticsEngine INSTANCE = new StatisticsEngine();
public boolean enabled = true;
private ConcurrentHashMap statsMap = new ConcurrentHashMap();
private StatisticsEngine() {
}
public static StatisticsEngine get() {
return INSTANCE;
}
public void inc(String name) {
MetricData m = lazyGet(name);
synchronized (m) {
m.increment();
}
}
public void inc(String name, long count) {
MetricData m = lazyGet(name);
synchronized (m) {
m.increment(count);
}
}
public void sample(String name, float value) {
MetricData m = lazyGet(name);
synchronized (m) {
m.sample((double) value);
}
}
public void sampleTimeMs(String name, long time) {
sample(name, ((float) time) / 1000.0f);
}
public static void populateMetrics() {
for (Entry entry : INSTANCE.getStatsMap().entrySet()) {
Queue.queue((MetricData) entry.getValue());
}
}
public void onHarvest() {
populateMetrics();
reset();
}
public static void reset() {
INSTANCE.getStatsMap().clear();
}
public static synchronized void disable() {
synchronized (StatisticsEngine.class) {
INSTANCE.enabled = false;
}
}
public static synchronized void enable() {
synchronized (StatisticsEngine.class) {
INSTANCE.enabled = true;
}
}
public ConcurrentHashMap getStatsMap() {
return this.statsMap;
}
private MetricData lazyGet(String name) {
MetricData m = (MetricData) this.statsMap.get(name);
if (m == null) {
m = new MetricData(name);
if (this.enabled) {
this.statsMap.put(name, m);
}
}
return m;
}
}