View a markdown version of this page

Profile a Java application on Amazon EC2 - Amazon CloudWatch

Profile a Java application on Amazon EC2

Install the CloudWatch agent and the AWS Distro for OpenTelemetry (ADOT) Java agent on an Amazon EC2 instance, and send continuous profiles from a sample Java application to Amazon CloudWatch Profiles.

When you finish, a sample Java application named example-java-service runs on an Amazon Linux 2023 instance with the ADOT Java agent. The async-profiler that's embedded in the ADOT Java agent sends one profile every 60 seconds to the CloudWatch agent on the same instance. The CloudWatch agent signs each request to the CloudWatch profiles endpoint with AWS Signature Version 4 (SigV4), using the credentials of the instance role. You then find the service and its flame graphs in CloudWatch.

Time to complete: About 20 minutes

Cost to complete: There is no charge for Amazon CloudWatch Profiles during the preview. Standard Amazon EC2 charges apply for the instance that you run.

Prerequisites

Before you begin, make sure that you have the following:

Step 1: Install and configure the CloudWatch agent

The CloudWatch agent doesn't use a separate configuration key for profiles. When you configure the otlp source under opentelemetry.collect, the agent also forwards the profile data that it receives on the same OpenTelemetry Protocol (OTLP) port. The agent signs each request with the credentials of the instance role.

To install and configure the CloudWatch agent
  1. Connect to your instance.

  2. Install the CloudWatch agent. Profiles need the CloudWatch agent version 1.300075.0 or later, which is the first release with OTLP profiles support.

    sudo dnf install -y amazon-cloudwatch-agent

    Alternatively, download the agent package from Amazon S3 and install it. On an arm64 instance, replace amd64 with arm64 in the URL.

    curl -sSLO https://amazoncloudwatch-agent.s3.amazonaws.com/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm sudo rpm -U ./amazon-cloudwatch-agent.rpm
  3. Create the agent configuration file /opt/aws/amazon-cloudwatch-agent/etc/profiles-getting-started.json with the following content. Replace region with the AWS Region where you want to store the profile data, for example, us-east-1.

    sudo tee /opt/aws/amazon-cloudwatch-agent/etc/profiles-getting-started.json >/dev/null <<'EOF' { "agent": { "region": "region" }, "opentelemetry": { "collect": { "otlp": { "http_endpoint": "127.0.0.1:4318" } } } } EOF

    This configuration makes the agent listen for OTLP data over HTTP on port 4318. The 127.0.0.1 address accepts data only from processes on the same instance. The ADOT Java agent sends profiles over HTTP, so you don't need a gRPC endpoint.

  4. Load the configuration and start the agent.

    sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \ -a fetch-config -m ec2 -s \ -c file:/opt/aws/amazon-cloudwatch-agent/etc/profiles-getting-started.json

    The fetch-config action replaces any earlier agent configuration, and the -s option restarts the agent.

Step 2: Confirm that the agent is ready to receive profiles

Before you start the application, confirm that the agent runs, that it listens on port 4318, and that it built a profiles pipeline. An agent version without profiles support accepts the same configuration without an error, but it doesn't forward profile data.

To confirm that the agent is ready
  1. Check the agent status.

    sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a status

    The output shows "status": "running".

  2. Check that the agent listens on port 4318.

    ss -ltn | grep 4318

    The output shows a listening socket on 127.0.0.1:4318. The agent might take a few seconds to open the port after it starts.

  3. Check the agent log for the startup messages.

    sudo grep -E 'Starting HTTP server|Everything is ready' \ /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log | tail -n 4

    The output includes a line that contains "msg":"Starting HTTP server" and "endpoint":"127.0.0.1:4318", and a line that contains "msg":"Everything is ready. Begin running and processing data.". The log keeps lines from earlier runs, so look at the most recent lines.

  4. Confirm that the agent built a profiles pipeline.

    sudo grep 'profiles/otlp' /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.yaml

    The output includes profiles/otlp. If the command returns nothing, your agent version doesn't support profiles. Install a version that supports profiles, and then repeat Step 1.

Step 3: Install Java and the ADOT Java agent

The sample application runs on Amazon Corretto 21. Version 2.32.0 and later of the ADOT Java agent embed async-profiler, so you don't install a separate profiler.

To install Java and the ADOT Java agent
  1. Install Amazon Corretto 21.

    sudo dnf install -y java-21-amazon-corretto-headless

    The headless package is enough to run the sample application.

  2. Create a directory for the ADOT Java agent.

    sudo mkdir -p /opt/aws-opentelemetry-agent
  3. Download the ADOT Java agent version 2.32.0 to the directory.

    sudo curl -sSfLo /opt/aws-opentelemetry-agent/aws-opentelemetry-agent.jar \ https://github.com/aws-observability/aws-otel-java-instrumentation/releases/download/v2.32.0/aws-opentelemetry-agent.jar
  4. Verify the checksum of the file.

    (cd /opt/aws-opentelemetry-agent && \ curl -sSfL https://github.com/aws-observability/aws-otel-java-instrumentation/releases/download/v2.32.0/aws-opentelemetry-agent.jar.sha256 \ | sha256sum -c -)

    The output shows aws-opentelemetry-agent.jar: OK.

    This check detects a corrupted or incomplete download. The checksum comes from the same GitHub release as the agent. If you change the ADOT Java agent version, change it in both URLs.

Step 4: Run the sample application with profiling turned on

The sample application does CPU-bound work and allocates memory in a loop until you stop it. Most of its CPU time goes to the computePrimes and isPrime methods. The allocateBuffers and hashStrings methods allocate memory. In production, use your own application and service name instead.

To run the sample application
  1. Create a directory for the sample application, and change to it.

    mkdir -p ~/profiles-sample && cd ~/profiles-sample
  2. Create a file named Main.java with the following content.

    // Sample for CloudWatch Profiles. Runs until stopped. import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws Exception { System.out.println("example-java-service started. Press Ctrl+C to stop."); long checksum = 0; while (true) { checksum += computePrimes(); checksum += hashStrings(); checksum += allocateBuffers(); if (checksum == 42) System.out.println(checksum); // keeps the JIT from removing the work } } // Uses most of the CPU time: look for Main.computePrimes and Main.isPrime. static long computePrimes() { long count = 0; for (int n = 2; n < 200_000; n++) { if (isPrime(n)) count++; } return count; } static boolean isPrime(int n) { for (int d = 2; (long) d * d <= n; d++) { if (n % d == 0) return false; } return true; } // Allocates strings: look for Main.hashStrings in the memory profiles. static long hashStrings() { long h = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100_000; i++) { sb.setLength(0); sb.append("example-").append(i); h += sb.toString().hashCode(); } return h; } // Allocates byte arrays: look for Main.allocateBuffers in the memory profiles. static long allocateBuffers() { List<byte[]> buffers = new ArrayList<>(); for (int i = 0; i < 2_000; i++) { buffers.add(new byte[16 * 1024]); } return buffers.size(); } }
  3. Start the application with the ADOT Java agent and the profiler turned on.

    OTEL_SERVICE_NAME="example-java-service" \ OTEL_AWS_PROFILER_ENABLED="true" \ OTEL_AWS_PROFILER_MEMORY_ENABLED="true" \ OTEL_TRACES_EXPORTER="none" \ OTEL_METRICS_EXPORTER="none" \ OTEL_LOGS_EXPORTER="none" \ java -javaagent:/opt/aws-opentelemetry-agent/aws-opentelemetry-agent.jar Main.java

    The application prints example-java-service started. Press Ctrl+C to stop. and keeps running. The output also includes a line that contains Started async-profiler. Leave the application running while you complete the next step.

The command uses the following environment variables:

  • OTEL_SERVICE_NAME – The service name that the ADOT Java agent adds to each profile as the service.name resource attribute. You find the profile data by this name.

  • OTEL_AWS_PROFILER_ENABLED – Turns on the profiler that's embedded in the ADOT Java agent.

  • OTEL_AWS_PROFILER_MEMORY_ENABLED – Turns on memory profiling, which the ADOT Java agent leaves off by default and the Kubernetes paths turn on.

  • OTEL_TRACES_EXPORTER, OTEL_METRICS_EXPORTER, and OTEL_LOGS_EXPORTER – This tutorial sends only profiles, so these variables turn off the export of traces, metrics, and logs. If you also want to send traces, metrics, and logs through the CloudWatch agent, remove these variables.

You don't need to set an endpoint. By default, the profiler sends profiles to http://localhost:4318/v1development/profiles, which matches the HTTP endpoint in the agent configuration from Step 1.

With these settings, the profiler collects wall-clock profiles, which sample threads both on and off the CPU, and memory allocation profiles. For more information about how to change the profiling mode, the sampling intervals, or the profile length, see the ADOT Java agent variables in Profile your application.

Step 5: Verify that profiles arrive in CloudWatch

The first profiles arrive about 1–3 minutes after the application starts. To find the service and its flame graphs, follow the steps in Verify that profile data is arriving. Look for the service example-java-service and the following profile types:

  • wall:wall:nanoseconds:wall:nanoseconds – The flame graph includes Main.computePrimes and Main.isPrime. It also shows idle threads, because the wall-clock mode also samples threads that aren't running.

  • memory:alloc_objects:count:alloc_objects:count – The flame graph shows Main.allocateBuffers and Main.hashStrings.

  • memory:alloc_space:bytes:alloc_space:bytes – The flame graph shows Main.allocateBuffers and Main.hashStrings.

Note

The flame graphs also include frames such as com/sun/tools/javac/launcher/Main.main. These frames appear when you run a single source file with java Main.java, because Java compiles the file when it starts. A packaged application doesn't show them.

Step 6: Clean up

To stop sending profile data, stop the sample application. If you don't use the CloudWatch agent for other data, you can also stop the agent. To avoid further charges, delete the files that you created, and terminate the instance if you launched it only for this tutorial.

To clean up
  1. In the terminal where the sample application runs, press Ctrl+C.

  2. (Optional) Stop the CloudWatch agent.

    sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a stop

    The agent configuration from Step 1 replaced any earlier configuration. If the agent sent other data before this tutorial, load your earlier configuration again instead of stopping the agent.

  3. (Optional) Delete the sample application and the ADOT Java agent.

    rm -rf ~/profiles-sample sudo rm -rf /opt/aws-opentelemetry-agent
  4. (Optional) If you launched the instance only for this tutorial, terminate the instance to stop Amazon EC2 charges.

Troubleshoot profiling on Amazon EC2

The following issues can occur when you set up profiling on Amazon EC2.

  • The profiler doesn't start

    When the profiler starts, the ADOT Java agent writes a line that contains Started async-profiler to the output of the application. If this line doesn't appear, check that OTEL_AWS_PROFILER_ENABLED is set to true and that the -javaagent path points to the ADOT Java agent version 2.32.0 or later. Profiling supports HotSpot Java virtual machines (JVMs) on Linux x64 and arm64.

  • No profile data in CloudWatch

    Check the following causes:

    • The agent has no profiles pipeline. If grep 'profiles/otlp' on /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.yaml returns nothing, your agent version doesn't support profiles. Install a version that supports profiles, and load the configuration again.

    • The agent isn't running. Run amazon-cloudwatch-agent-ctl -a status, and check /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log for errors.

    • The profiler endpoint doesn't match the agent configuration. The profiler sends to http://localhost:4318/v1development/profiles by default. If you changed the http_endpoint port in the agent configuration, or set OTEL_AWS_PROFILER_ENDPOINT, make sure that both use the same HTTP port.

    • The application output shows that the profiler data directory isn't writable. Set OTEL_AWS_PROFILER_DATA_DIR to a directory that the user who runs the application can write to, and restart the application.

    • Not enough time has passed. The profiler sends the first profile after the first 60-second window. Wait 2–3 minutes, and then check again.

  • You get an access denied error when you view profile data

    The credentials that you use need the cloudwatch:GetProfileRecords permission. The CloudWatchAgentServerPolicy policy doesn't include it. For more information, see IAM permissions required.

Next steps

Now that profile data arrives in CloudWatch, you can do the following:

For more information, see the following topics: