import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordingFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;

public class MethodTraceBugs {

    public static void main(String[] args) throws Exception {
        var settings = new HashMap<String, String>();
        settings.put("jdk.MethodTrace#enabled", "true");
        settings.put("jdk.MethodTrace#stackTrace", "true");
        settings.put("jdk.MethodTrace#threshold", "250 ms");
        settings.put("jdk.MethodTrace#filter", Tracing.class.getName());

        Path path = Paths.get("/tmp/tracing.jfr");

        try (var r = new Recording(settings)) {
            r.setDestination(path);
            r.start();

            for (int i = 1; i <= 5; i++) {
                Tracing.sleepAndThrow(i * 100);
            }

            r.stop();
        }

        try (RecordingFile f = new RecordingFile(path)) {
            int calls = 0;
            int belowThreshold = 0;

            while (f.hasMoreEvents()) {
                calls++;
                if (f.readEvent().getDuration().toMillis() < 250) belowThreshold++;
            }

            System.out.println("Recorded calls: " + calls + ", expected: 5");
            System.out.println("Calls below threshold: " + belowThreshold + ", expected: 0");
        }

        Files.deleteIfExists(path);
    }

    public static class Tracing {

        public static void sleepAndThrow(long delay) {
            System.out.println("Sleeing for " + delay + " ms");
            try {
                Thread.sleep(delay);
                throw new RuntimeException();
            } catch (Exception ignore) {
            }
        }
    }
}
