oracle / visualvm

VisualVM is an All-in-One Java Troubleshooting Tool
https://visualvm.github.io/
Other
2.89k stars 305 forks source link

Can we Automate/Schedule Heap and Thread Dump at regular interval of Time #192

Open venkategowdap opened 4 years ago

venkategowdap commented 4 years ago

Hi Team ,

Is it possible to automate/schedule Heap and Thread Dump at regular interval of Time ? , so that we can save metrics and use for Root Cause analysis .

Please suggest me the way if its already available on VisualVM

Thanks

jisedlac commented 4 years ago

Automating/scheduling thread/heap dumps is not available out of the box but can be easily achieved using a custom plugin. The following code snippets illustrate how to do it:

At first an instance of Application needs to be obtained - interactively for example using DataSourceAction<Application> or by code, for example by searching the set of local applications:

Set<Application> localApps = Host.LOCALHOST.getRepository().getDataSources(Application.class);
Application someLocalApp = localApps.iterator().next(); // use someLocalApp.getPid() to identify the right app by PID

Once you have the right Application instance, you can instruct VisualVM to take a thread/heap dump using this code:

ThreadDumpSupport.getInstance().takeThreadDump(someLocalApp, false);
HeapDumpSupport.getInstance().takeHeapDump(someLocalApp, false);

Use a timer class to repeat taking thread/heap dumps at the desired interval.

Eventually you can resolve the directory where all the created snapshots have been stored using:

File someLocalAppStoraget = someLocalApp.getStorage().getDirectory();

Or you can access the created snapshots one by one using:

Set<Snapshot> snapshots = someLocalApp.getRepository().getDataSources(Snapshot.class);
Snapshot firstSnapshot = snapshots.iterator().next(); // use firstSnapshot.getFile() to get handle to the snapshot file

Note that since VisualVM is designed as an interactive tool, controlling its functionality using the API needs a special attention. Most of the tasks are asynchronous, for example you have to wait for a few seconds after invoking a heap dump until the snapshot is taken and available.

jisedlac commented 3 years ago

Should now be easier to achieve using an external timer calling the new command-line options: #319 & #320.