Search code examples
javajfr

How can I programmatically check if JFR is recording?


Java Flight Recorder provides simple APIs to detect if it's available (FlightRecorder.isAvailable()) or initialized (FlightRecorder.isInitialized()). But there's no obvious API to detect if it's actually recording. Maybe I could check FlightRecorder.getFlightRecorder().getRecordings().isEmpty(), but I'm not sure it would be accurate. Is there an obvious API I'm missing?


Solution

  • To see if a recording is running, you must iterate all recordings and check their state.

    I added the initialization check to prevent JFR to initialize when FlightRecorder.getFlightRecorder() is called.

    public static boolean isRunning() {
      if (!FlightRecorder.isInitialized()) {
        return false;
      }
      for (Recording r : FlightRecorder.getFlightRecorder().getRecordings()) {
        if (r.getState() == RecordingState.RUNNING) {
          return true;
        }
      }
      return false;
    }
    

    If you want to detect when a recording starts, you can use the FlightRecorderListener.

    FlightRecorder.addListener(new FlightRecorderListener() {
      @Override
      public void recordingStateChanged(Recording recording) {
        if (recording.getState() == RecordingState.RUNNING) {
          ...
        }
      }
    });