package test;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import jdk.jfr.Configuration;
import jdk.jfr.FlightRecorder;
import jdk.jfr.Recording;


public class Test {

    public static void main(String[] args) throws Exception {

        Recording recording = startRecording();
        try {
            Thread.sleep(5_000);
        } finally {
            getAndDisposeRecording(recording);
        }
    }

    private static Recording startRecording() throws IOException, ParseException {
        if (!FlightRecorder.isAvailable()) {
            throw new IllegalStateException("JFR not supported by VM.");
        }
        Configuration cfg = Configuration.getConfiguration("default");
        Recording r = new Recording(cfg);
        r.setDestination(null);
        r.setDumpOnExit(false);
        r.setToDisk(false); // If removed the Recording#getStream works fine.
        r.start();
        return r;
    }

    private static void getAndDisposeRecording(Recording r) throws IOException {
        try {
            r.stop();
            try (InputStream in = r.getStream(null, null)) {
                if (in == null) {
                    throw new AssertionError(in);
                }
            }
        } finally {
            r.close();
        }
    }
}
