JProfiler Help

Gradle Tasks

JProfiler supports profiling from Gradle with special tasks. In addition. JProfiler offers a number of command line executables for working with snapshots that have corresponding Gradle tasks.

Using Gradle tasks

To make the JProfiler Gradle tasks available in a Gradle build file, you can use the plugins block

plugins {
    id 'com.jprofiler' version 'X.Y.Z'
}

If you do not want to use the Gradle plugin repository for this purpose, the Gradle plugin is distributed in the file bin/gradle.jar.

Next, you have to tell the JProfiler Gradle plugin where JProfiler is installed.

jprofiler {
    installDir = file('/path/to/jprofiler/home')
}

Profiling from Gradle

With tasks of type com.jprofiler.gradle.JavaProfile you can profile any Java process. This class extends Gradle's built-in JavaExec, so you can use the same arguments for configuring the process. For profiling tests, use tasks of type com.jprofiler.gradle.TestProfile that extend the Gradle Test task.

Without any further configuration, both tasks start an interactive profiling session where the profiling agent waits on default port 8849 for a connection from the JProfiler GUI. For offline profiling, you can either reference an exported config file or configure common session settings and automated recording directly with the attributes shown in the table below.

Attribute Description Required
offline Whether the profiling run should be in offline mode. No, offline and nowait cannot both be true.
nowait Whether profiling should start immediately or whether the profiled JVM should wait for a connection from the JProfiler GUI.
sessionId Defines the session ID from which profiling settings should be taken. Has no effect if neither nowait nor offline are set because in that case the profiling session is selected in the GUI. Only if configFile is set for offline profiling
configFile Defines the config file from which the profiling settings should be read. If this attribute is omitted for offline profiling, common session settings can be configured directly with the attributes below. If none of these attributes are set, default offline session settings are used. No
callTreeMode Selects the call tree collection mode for config-less offline profiling. In Gradle, values of com.jprofiler.buildtools.CallTreeMode can be used. String values are sampling, instrumentation, instr and async. No
profile, compact, ignore Package or class filters for config-less offline profiling. Values can be strings with entries separated by :, or lists of strings. No
lineNumbers Whether line numbers should be recorded in call trees. No
snapshotFile Snapshot file for an automated offline recording. If this is set without recording, CPU data is recorded. Threads and telemetry are always recorded. No
recording Data types for an automated offline recording. Values can be strings with entries separated by :, or lists of strings. Common values are cpu, allocation, jdbc, jpa, mongo_db, http_server and http_client. The full list of supported recording values is documented for the corresponding -agentpath option. Selecting a probe recording also records CPU data. No, but requires snapshotFile if set
duration Duration of an automated offline recording, for example 30s, 10m or 1h. Without this attribute, recording continues until the JVM terminates and the snapshot is saved then. No, but requires snapshotFile if set
delay Delay before an automated offline recording starts, for example 10s or 1m. No, but requires snapshotFile if set
port Defines the port number on which the profiling agent should listen for a connection from the JProfiler GUI. This must be the same as the port configured in the remote session configuration. If not set or zero, the default port (8849) will be used. Has no effect if offline is set because in that case there is no connection from the GUI. No
debugOptions If you want to pass any additional library parameters for tuning or debugging purposes, you can do that with this attribute. No

An example for profiling a Java class with a main method that is compiled by the containing project is given below:

task run(type: com.jprofiler.gradle.JavaProfile) {
    mainClass = 'com.mycorp.MyMainClass'
    classpath sourceSets.main.runtimeClasspath
    offline = true
    callTreeMode = 'sampling'
    profile = ['com.mycorp.', 'org.example.']
    snapshotFile = file('build/snapshots/run.jps')
    recording = ['cpu', 'allocation', 'jdbc']
    duration = '10m'
}

For advanced settings that are not covered by the config-less attributes, export a config file and reference it with configFile and sessionId.

task run(type: com.jprofiler.gradle.JavaProfile) {
    mainClass = 'com.mycorp.MyMainClass'
    classpath sourceSets.main.runtimeClasspath
    offline = true
    sessionId = 80
    configFile = file('path/to/jprofiler_config.xml')
}

You can see a runnable example of this task in the api/samples/offline sample project. Unlike the standard JavaExec task, the JavaProfile task can also be started in the background by calling createProcess() on it. See the api/samples/mbean sample project for a demonstration of this feature.

If you need the VM parameter that is required for profiling, the com.jprofiler.gradle.SetAgentpathProperty task will assign it to a property whose name is configured with the propertyName attribute. Applying the JProfiler plugin automatically adds a task of this type named setAgentPathProperty to your project. For getting the VM parameter that would be used in the previous example, you can simply add

setAgentPathProperty {
    propertyName = 'profilingVmParameter'
    offline = true
    callTreeMode = 'sampling'
    profile = ['com.mycorp.', 'org.example.']
}

to your project and add a dependency to setAgentPathProperty to some other task. Then you can use the project property profilingVmParameter in the execution phase of that task. When assigning the property to other task properties, surround its usage with a doFirst {...} code block in order to make sure that you are in the Gradle execution phase and not in the configuration phase.

Exporting data from snapshots

The com.jprofiler.gradle.Export task can be used to export views from a saved snapshot and replicates the arguments of the bin/jpexport command line tool. It supports the following attributes:

Attribute Description Required
snapshotFile The path to the snapshot file. This must be a file with a .jps extension. Yes
ignoreErrors Ignore errors that occur when options for a view cannot be set and continue with the next view. The default value is false, meaning that the export is terminated when the first error occurs. No
csvSeparator The field separator character for the CSV exports. Defaults to ",". No
obfuscator Deobfuscate class and method names for the selected obfuscator. Defaults to "none", for other values the mappingFile option has to be specified. One of none, proguard or yguard. No
mappingFile The mapping file for the selected obfuscator. May only be set if the obfuscator attribute is specified. Only if obfuscator is specified

On the export task, you call the views method and pass a closure to it in which you call view(name, file[, options]) one or multiple times. Each call to view produces one output file. The name argument is the view name. For a list of available view names, please see the help page on the jpexport command line executable. The argument file is the output file, either an absolute file or a file relative to the project. Finally, the optional options argument is a map with the export options for the selected view.

An example for using the export task is:

task export(type: com.jprofiler.gradle.Export) {
    snapshotFile = file('snapshot.jps')
    views {
        view('CallTree', 'callTree.html')
        view('HotSpots', 'hotSpots.html',
            [threadStatus: 'all', expandBacktraces: 'true'])
    }
}

Comparing snapshots

Like the bin/jpcompare command line tool, the com.jprofiler.gradle.Compare task can compare two or more snapshots. Its attributes are:

Attribute Description Required
snapshotFiles The snapshot files that should be compared. You can pass any Iterable containing objects that Gradle resolves to file collections.

If snapshot files have individual deobfuscation settings, the file names can be of the form <file name>:<Mobfuscator>:<mapping file> where <obfuscator> and <mapping file> correspond the to the global options below.

Yes
obfuscator Deobfuscate class and method names for the selected obfuscator. Defaults to "none", for other values the mappingFile option has to be specified. One of none, proguard or yguard. No
mappingFile The mapping file for the selected obfuscator. May only be set if the obfuscator attribute is specified. Only if obfuscator is specified
sortByTime If set to true all supplied snapshots files are sorted by their file modification time, otherwise they are compared in the order they were specified in the snapshotFiles attribute. No
ignoreErrors Ignore errors that occur when options for a comparison cannot be set and continue with the next comparison. The default value is false, meaning the export is terminated when the first error occurs. No

Just like exported views are defined for the Export task, the Compare task has a comparisons method where nested calls to comparison(name, file[, options]) define the comparisons that should be performed. The list of available comparison names is available on the help page of the jpcompare command line executable.

An example for using the compare task is:

task compare(type: com.jprofiler.gradle.Compare) {
    snapshotFiles = files('snapshot1.jps', 'snapshot2.jps')
    comparisons {
        comparison('CallTree', 'callTree.html')
        comparison('HotSpots', 'hotSpots.csv',
            [valueSummation: 'total', format: 'csv'])
    }
}

or, if you want to create a telemetry comparison for multiple snapshots:

task compare(type: com.jprofiler.gradle.Compare) {
    snapshotFiles = fileTree(dir: 'snapshots', include: '*.jps')
    sortByTime = true
    comparisons {
        comparison('TelemetryHeap', 'heap.html', [valueType: 'maximum'])
        comparison('ProbeTelemetry', 'jdbc.html', [probeId: 'JdbcProbe'])
    }
}

Analyzing heap snapshots

The gradle task com.jprofiler.gradle.Analyze has the same functionality as the bin/jpanalyze command line tool.

The task has a snapshotFiles attribute like the Compare task to specify the processed snapshots and obfuscator and mappingfile attributes like the Export task for deobfuscation. The attributes removeUnreferenced, retainSoft, retainWeak, retainPhantom, retainFinalizer and retained correspond the arguments of the command line tool.

An example for using the Analyze task is given below:

task analyze(type: com.jprofiler.gradle.Analyze) {
    snapshotFiles = fileTree(dir: 'snapshots', include: '*.jps')
    retainWeak = true
    obfuscator = 'proguard'
    mappingFile = file('obfuscation.txt')
}