Writing a Profiler in 240 lines of pure Java
mostlynerdless.de
mostlynerdless.de
I write a blog post on this and related in-depth profiling topics every two weeks (you can follow me on social media https://twitter.com/parttimen3rd and https://mastodon.social/@parttimenerd to get notified).
I believe the code of the constructor of Profiler is not thread safe, it has a publication problem. The method onEnd can be called by the profiler thread while the fields options and store are not fully initialized.
From another thread POV, a final field is only fully initialized after the call to the constructor not inside the call to the constructor.
I believe the issue is between the profiler thread and the shutdown hook thread. Both will run concurrently because the profiler thread is marked deamon. So the shutdown hook thread can see the Profiler fields not fully initialized. The call to addShutdownHook() should be done outside of the Profiler constructor.
public static Profiler newInstance(Options options) {
Profiler profiler = new Profiler(options);
Runtime.getRuntime().addShutdownHook(new Thread(profiler::onEnd));
return profiler;
}
private Profiler(Options options) {
this.options = options;
this.store = new Store(options.getFlamePath());
}
In principle you can also use chained constructors: public Profiler(Options options) {
this(options, null);
Runtime.getRuntime().addShutdownHook(new Thread(this::onEnd)); // okay to leak this here
}
private Profiler(Options options, Void dummy) {
this.options = options;
this.store = new Store(options.getFlamePath());
}
(cf. https://stackoverflow.com/a/35169705/623763)Actually, is there anything stopping the sampler from taking another sample while onExit is running?
Re the multi-threading issue, it should be possible to stop the profiler thread in the hook, if we keep a reference to the thread, no?
https://github.com/openjdk/jdk/blob/2fa09333ef0ac2dc1e44292f8d45d4571cb22cca/src/java.base/share/classes/java/lang/Runtime.java#L69
https://github.com/openjdk/jdk/blob/2fa09333ef0ac2dc1e44292f8d45d4571cb22cca/src/java.base/share/classes/java/lang/ApplicationShutdownHooks.java#L65
maybe I'm missing something that is java specific with the way constructors work. I'm guessing even without the synchronisation point java lets you share objects in a way that would normally be considered unsafe as long as all the fields are final. var r = new RecordingStream();
r.enable("jdk.ExecutionSample").withStackTrace().withPeriod(Duration.ofMillis(1));
r.onEvent("jdk.ExecutionSample", e -> {
store.addSample(e.getStackTrace().getFrames());
});
r.startAsync();
...> demo1: ... JFR will not report anything useful at all, since it cannot traverse stack traces when JVM is running System.arraycopy()
I'd rather run jstack in a loop than lose System.arraycopy() (or, in fact, any native code be it JVM's or JNI).
That's why I was querying it's suitability for profiling. The time to get a lock for a global "safepoint" and then release it must be significant no?
They are not. There are orders of magnitude more rocket scientists than good profiler writers. And no, bottle rockets with flight recorders do not count.
There are even fewer people working on the underlying profiling APIs. I'm one of the few working regularly on the stack walking API that powers most Application Platform Monitors (and async-profiler). I'm the person who writes all the code to test AsyncGetCallTrace currently. If anyone is interested: I wrote a blog post on it https://mostlynerdless.de/blog/2023/03/14/validating-java-pr....
I'm writing blog posts on the profiling topic every two weeks (usually publishing them on Monday or Tuesday).
I don't doubt my favorite profiler, YourKit also uses your code.
Profilers are probably the class of tool that most drastically improved the code I write so if anyone reading hasn't really felt the need to use one, you should.
Just a cursory glance can quickly verify assumptions about runtime performance. Even if the code is currently acceptable it helps to be mindful of where cycles are being spent (and lock contention, network blocking, etc) so if you end up doing some refactoring anyway that additional context and knowledge can guide improvements that aren't strictly "performance work".
It's just a game of whack-a-mole, finding new segmentation faults and other bugs is quite easy when you know how to write good test code. Fixing the actual bugs less so. But it's fun and I do this for a living in the SapMachine team at SAP SE.
> I don't doubt my favorite profiler, YourKit also uses your code.
They surely do profit by work improving the profiling APIs.
> Just a cursory glance can quickly verify assumptions about runtime performance.
Yes. But there aren't enough people educating people on profilers. So I started blogging and talking (https://youtu.be/Fglxqjcq4h0) on this topic. Besides fixing all the bugs and implementing my own profile viewer based on FirefoxProfiler (https://plugins.jetbrains.com/plugin/20937-java-jfr-profiler).
This approach forces a safepoint and therefore all results will be safepoint biased. That's a very good way to mislead oneself about where the cpu time goes.
The correct way is to employ asynchronous stack probing like async profiler or any other modern profiler does.
"Writing a Java profiler in 240 lines of pure Java is possible and the resulting profiler could even be used to analyze performance problems. This profiler is not designed to replace real profilers like async-profiler, but it demystifies the inner workings of simple profilers."
And you'll find a large disclaimer on top of the article explaining the safepoint-bias and linking to relevant blog posts by other people on this topic.
Please don't use this profiler in production, but you use it to further your knowledge of profilers.
> The correct way is to employ asynchronous stack probing like async profiler or any other modern profiler does.
Guess what my other articles on my blog are about :) But as you'll see, using the asynchronous APIs is far harder and requires knowledge on POSIX signals, C programming and more that many Java developers do not have.