• EnglishEspañol日本語한국어Português
  • Log inStart now

Java agent API for asynchronous applications

New Relic for Java (agent version 3.37 or higher) includes an API to instrument asynchronous activity. For supported frameworks, the agent usually instruments async work automatically. However, the async API can still be useful to add detail. This document provides examples of using tokens and segments to instrument your app.

Async tracking tools: Tokens and segments

The Java agent API provides two ways to trace asynchronous activity:

  • Tokens: Tokens are passed between threads to link asynchronous units of work to a specific transaction. They do not perform any timing directly.
  • Segments: Segments are used to measure an arbitrary piece of asynchronous application code, not necessarily associated with a method or thread. Segments are typically used to track external calls that are completed by a callback mechanism.

Tokens: Connect async threads

Use tokens to link arbitrary units of work that are on separate threads. This section describes how to use the token-related calls together to instrument async work. For detailed information on classes and methods, see the Javadoc.

To use tokens, you first need to create the token, then link another call to the originating transaction. You should link the token as soon as possible within the other call. If you do not link the token immediately, you risk losing any methods that contain an @Trace below the call you are trying to link. You can also expire the token in the original call. The Java agent will then link the work in the New Relic UI. These examples illustrate how to use the token-related calls together:


By default, a transaction can create a maximum of 3000 tokens and each token has a default timeout of 180s. You can change the former limit with the token_limit config option and the latter with the token_timeout config option. Traces for transactions that exceed the token_limit will contain a token_clamp attribute. Increasing either config option may increase agent memory usage.

Segments: Time arbitrary async activity

Segments are used to measure an arbitrary piece of asynchronous application code, not necessarily associated with a method or thread. This is most commonly used to time connections to external services. Use segments if you want to:

  • Time code that completes via a callback
  • Time an asynchronous call that spans many methods
  • Measure the time between when work is created and when it executed (for example, in a thread pool)


By default, the agent can track a maximum of 1000 segments during a given transaction. You can change this limit with the segment_timeout config option. Traces of transactions that exceed this limit will contain a segment_clamp attribute. Increasing this limit may increase agent memory usage.

Copyright © 2024 New Relic Inc.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.