Thanks. But this should only be a problem if the JVM terminates too fast, or am I wrong?
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?