Skip to content

Commit

Permalink
Add java percentile timer documentation.
Browse files Browse the repository at this point in the history
  • Loading branch information
manolama committed Jun 7, 2024
1 parent 40edf71 commit dc20266
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion docs/spectator/lang/java/meters/percentile-timer.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,51 @@
# Java Percentile Timers

TBD
**Note**: Percentile timers generate a metric per bucket in the histogram. Create instances
once per ID and reuse them as needed. Avoid adding tags with high cardinality as that increases
the cardinality of the metric. If at all possible, use a [Timer](timer.md) instead.

To get started, create an instance using the [Registry](../registry/overview.md):

```java
public class Server {

private final Registry registry;
private final PercentileTimer requestLatency;

@Inject
public Server(Registry registry) {
this.registry = registry;
requestLatency = PercentileTimer.builder(registry)
.withId(registry.createId("server.request.latency", "status", "200"))
.build();
```

Then wrap the call you need to measure, preferably using a lambda:

```java
public Response handle(Request request) {
return requestLatency.recordRunnable(() -> handleImpl(request));
}
```

The lambda variants will handle exceptions for you and ensure the record happens as part of a
finally block using the monotonic time. It could also have been done more explicitly like:

```java
public Response handle(Request request) {
final long start = registry.clock().monotonicTime();
try {
return handleImpl(request);
} finally {
final long end = registry.clock().monotonicTime();
requestLatency.record(end - start, TimeUnit.NANOSECONDS);
}
}
```

This example uses the Clock from the Registry, which can be useful for testing, if you need
to control the timing. In actual usage, it will typically get mapped to the system clock. It
is recommended to use a monotonically increasing source for measuring the times, to avoid
occasionally having bogus measurements due to time adjustments. For more information, see the
[Clock documentation](../../../core/clock.md).

0 comments on commit dc20266

Please sign in to comment.