All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.marschall.micrometer.jfr.JfrFunctionCounter Maven / Gradle / Ivy

There is a newer version: 1.13.0
Show newest version
package com.github.marschall.micrometer.jfr;

import java.lang.ref.WeakReference;
import java.util.function.ToDoubleFunction;

import io.micrometer.core.instrument.FunctionCounter;

final class JfrFunctionCounter extends AbstractJfrMeter implements FunctionCounter {

  private final WeakReference reference;
  private final ToDoubleFunction countFunction;
  private final Runnable hook;

  JfrFunctionCounter(Id id, T obj, ToDoubleFunction countFunction) {
    super(id, new FunctionCounterEventFactory(id));
    // all the other code uses a WeakReference
    this.reference = new WeakReference<>(obj);
    this.countFunction = countFunction;
    this.hook = () -> this.count();
    this.meterEventFactory.registerPeriodicEvent(this.jfrEventFactory, this.hook);
  }

  @Override
  public void close() {
    this.meterEventFactory.unregisterPeriodicEvent(this.hook);
    super.close();
  }

  @Override
  public double count() {
    T obj = this.reference.get();
    double value;
    if (obj != null) {
      value = this.countFunction.applyAsDouble(obj);
    } else {
      value = Double.NaN;
    }
    JfrFunctionCounterEvent event = this.newEmptyEvent();
    event.setCount(value);
    event.commit();
    return value;
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy