mesibo
mesibo

Reputation: 4333

Java - function profiling

We have a java program. I would like to track entry and returns of a few functions by calling appropriate profiler functions on the entry and returns of those functions.

Tracking a function entry is simple so won't be part of this discussion. However, return is a bit messy as we would have to add profiler code at every return points, and hence looking for suggestions how best we can do without cluttering the code.

In C++, it was easy, just create a local instance of a small trace class at entry of the function and the constructor and destructor of that trace class would take care of calling profiler function. However, java has no destructor (finalize won't work) so that approach is out of question.

Any suggestions/tips?

Upvotes: 3

Views: 702

Answers (2)

Kire Haglin
Kire Haglin

Reputation: 7069

If you are on JDK 11 and want to measure the time a method execute with very low overhead you could create a Flight Recorder event.

@StackTrace(false)
static class StopWatch extends jdk.jfr.Event {
}

StopWatch s = new StopWatch();
try {
  s.begin();
  ...
} finally {
  s.commit();
}

To record, start the JVM with:

java -XX:StartFlightRecording:filename=dump.jfr

and the recording will be written when the JVM exists. It can then be opened in JDK Mission Control. That said, adding instrumentation to hot methods may skew the results and sampling is usually a better approach, in which case you can just use Flight Recorder as is without the added code.

Upvotes: 2

Ingo Kegel
Ingo Kegel

Reputation: 48080

Use a try/finally block over the whole method body:

// handle entry
try {
    // function body
} finally {
    // handle return
}

Upvotes: 2

Related Questions