Search code examples
javaprofilervisualvm

Is there a way to start or stop data collection from the profiled application?


I would like to profile a certain part of the execution of a small application. Is there a way to trigger the data collection in VisualVM from within the application that is to be profiled? In other words, is it possible to add code to the profiled application so that the profiling in VisualVM will start automatically once this code is hit?

meaninglessCode();

// How to start data collection?
com.sun.tools.visualvm.....startSampling();
//

codeToBeProfiled();

// How to stop data collection?
com.sun.tools.visualvm.....stopSampling();
//

furtherMeaninglessCode();

My current workaround is a Thread.sleep call that gives me time to push the button in the VisualVM GUI, but this is far from satisfactory. Several Google searches didn't show any success. I appreciate any hint.


Solution

  • You may use two VisualVM settings to customize the profiling session as described in this blog entry:

    • Profiling roots: Put class containing codeToBeProfiled()
    • Instrumentation filters: Define your own or leave default value

    This way, VisualVM will start profiling when any method of the class containing codeToBeProfiled() is executed.