skip to content

Java Agents & Instrumentation API

What an agent JAR declares, how premain and agentmain get the Instrumentation handle, the transformer contract's traps, and retransform versus redefine. Asked when APM or coverage agents misbehave.

part ofJVM internalsread it →
on this pageshow

questions

6

A metrics agent JAR starts fine with -javaagent but fails to load into an already running JVM; what must a Java agent JAR declare for each start mode?

level: middleimportance: must knowfreq 35%

answer

  1. main manifest, one attribute per mode
  2. premain versus agentmain
  3. two-argument signature tried first
  4. launch failure aborts, attach failure does not
  5. capabilities are opt-in attributes

basics

~20 s

A Java agent JAR names its agent class in the main manifest, once per start mode: Premain-Class for -javaagent (premain), Agent-Class for loading into a running JVM (agentmain), Launcher-Agent-Class for an executable JAR (agentmain before main).

solid answer

~40 s

The JVM reads the agent JAR's main manifest. With `-javaagent:agent.jar=opts` it needs `Premain-Class` and calls `public static void premain(String agentArgs, Instrumentation inst)`, falling back to `premain(String)`, before `main`. Loading into a running JVM needs `Agent-Class` and a public static `agentmain` with the same two shapes; a JAR that declares only `Premain-Class` is refused, and the JDK's Attach API reports "Agent JAR not found or no Agent-Class attribute", which is this failure. A JAR may declare both, and each mode reads only its own attribute. `Launcher-Agent-Class` starts an agent bundled in an executable JAR through `agentmain` before `main`. Capabilities are opt-in: `Can-Retransform-Classes` and `Can-Redefine-Classes` default to false, and `Boot-Class-Path` adds JARs to the bootstrap search. A failing `premain` aborts start-up; a failing `agentmain` leaves the running JVM up and the attaching tool gets an error.

code

properties · 3 lines
properties
Premain-Class: com.acme.metrics.agent.MetricsAgent
Agent-Class: com.acme.metrics.agent.MetricsAgent
Can-Retransform-Classes: true

go deeper

for a junior

Recall that a Java agent is a JAR the JVM starts with a special entry method before or alongside the application, and that -javaagent is how you add one at launch.

for a middle

Name the attribute for each start mode, the two entry methods and their two signatures, and the Can-* attributes that gate retransformation and redefinition.

for a senior

Diagnose a failed start from the mode: a missing Agent-Class, a one-argument entry point without Instrumentation, or classes already loaded that need retransforming after a late load.

for a principal

Decide which start modes your agent supports at all, since launch-time agents abort start-up on failure while late-loaded ones fail softly and need their own visibility.

## What a Java agent is A **Java agent** is ordinary Java code, packaged in a JAR, that the JVM starts before or alongside the application and hands an `Instrumentation` object from the `java.lang.instrument` package. With that handle the agent can register `ClassFileTransformer`s that rewrite class bytes as classes load, retransform or redefine classes that are already loaded, extend the class search paths and estimate object sizes. Monitoring agents, coverage agents and mocking libraries all build on this contract. What makes a JAR an agent is not its code but its **main manifest**: one attribute tells the JVM which class to start, and the start mode decides which entry method it calls. ## Three start modes, three attributes | Start mode | How it is triggered | Manifest attribute | Method the JVM calls | When it runs | If start-up fails | |---|---|---|---|---|---| | Command line | `-javaagent:<jarpath>[=<options>]` | `Premain-Class` | `premain` | before the application's `main` | the JVM aborts | | Running JVM | an implementation-specific mechanism, such as the JDK's Attach API | `Agent-Class` | `agentmain` | whenever it is loaded | the JVM keeps running | | Executable JAR | `java -jar app.jar` with the agent packaged inside | `Launcher-Agent-Class` | `agentmain` | before `main` | the JVM aborts | A JAR may carry both `Premain-Class` and `Agent-Class`. Each start mode reads only its own attribute and ignores the other: `premain` is never called for an agent loaded into a running JVM, and `agentmain` is never called for a `-javaagent` one. The scenario in the question is the textbook case. The metrics JAR declared only `Premain-Class`, so `-javaagent` worked while the late load was refused. The JDK's Attach API reports it as an `AgentLoadException` reading "Agent JAR not found or no Agent-Class attribute", and the target JVM prints "Failed to find Agent-Class manifest attribute" on its standard error. ## The entry-point contract The JVM finds the entry method in a fixed order: 1. It loads the named agent class through the system class loader. 2. It looks for the two-argument form, `public static void premain(String agentArgs, Instrumentation inst)`, or `agentmain` with the same parameters. 3. If that is absent it falls back to the one-argument form, `premain(String agentArgs)`, which receives **no** `Instrumentation` handle. 4. It invokes the method; the JDK rejects a method that is not `public` with an `IllegalAccessException`. `agentArgs` is the whole option string after `=`, passed as one `String`; parsing it is the agent's job. For `Launcher-Agent-Class` the argument is always the empty string. Several `-javaagent` options may appear on one command line, even for the same JAR, and their `premain` methods run in command-line order. ## Capability and class-path attributes The entry attribute is only part of the manifest. The others are optional and default to off: - **`Can-Retransform-Classes`** must be `true` for `isRetransformClassesSupported()` to return true and for `addTransformer(t, true)` to be allowed. - **`Can-Redefine-Classes`** is the same gate for `redefineClasses` and `isRedefineClassesSupported()`. - **`Can-Set-Native-Method-Prefix`** allows `setNativeMethodPrefix`, used to wrap native methods, which have no bytecode to rewrite. - **`Boot-Class-Path`** lists space-separated paths the bootstrap loader searches after its own; relative paths resolve against the agent JAR's location, and for an agent loaded into a running JVM only JAR files are honoured. The boolean attributes ignore case, and any value other than `true` counts as false, so a typo silently disables a capability. ## Failure handling differs by mode The modes disagree on what a broken agent costs: - A missing `Premain-Class`, a missing or non-public `premain`, or a `premain` that throws makes the JVM **abort before `main`**. A launch-time agent is part of the application. - For an agent loaded into a running JVM, a missing class or method, or an `agentmain` that throws, does **not** stop the JVM. In the JDK the exception is logged in the target's output and the attaching tool receives an `AgentInitializationException`. - `agentmain` should do its set-up and return promptly, because the load request completes only when it does. ## Reading the scenario For the service that needs the agent without a restart, the fix is in the JAR, not the JVM: add `Agent-Class` (often naming the same class as `Premain-Class`), add a public static `agentmain(String, Instrumentation)`, and set `Can-Retransform-Classes: true`. The classes the agent must instrument were loaded before `agentmain` ran, so a newly registered transformer will not see them on its own; the agent has to retransform them, as the example shows.

  • What does an agent lose if its premain declares only the one-argument signature premain(String)?
    The JVM still starts it, but it receives no `Instrumentation` handle. Without one it cannot call `addTransformer`, `retransformClasses`, `redefineClasses`, the class-path append methods or `getObjectSize`, so it can only run code at start-up. The two-argument form is looked up first, which is why both may be declared and the richer one wins.
  • What happens when two -javaagent options appear on the same command line?
    Each one starts its own agent with its own `Instrumentation` instance, and their `premain` methods run in command-line order, before `main`. The same JAR may even appear twice. Transformers registered by the agents are then called in registration order within each group, so for a class both of them change, the first agent's output becomes the second one's input.
  • How does Launcher-Agent-Class differ from Premain-Class?
    `Launcher-Agent-Class` sits in the manifest of an executable JAR that is the application itself, started with `java -jar`. The JVM calls the agent class's `agentmain`, not `premain`, before `main`, and `agentArgs` is always the empty string. As with `Premain-Class`, a failure to start the agent aborts the JVM before `main`.

  • Premain-Class alone is enough to load an agent into a running JVM.
  • agentmain only ever runs in a JVM that has already started main.
  • If both Premain-Class and Agent-Class are present, both entry points are called.
  • A premain that throws is logged and the application starts without the agent.
  • Every agent can retransform classes; no manifest attribute is needed.
open as a page

An in-house metrics agent's ClassFileTransformer is registered in premain, yet one target class loads untransformed and nothing is logged; what in the transformer contract explains that?

level: seniorimportance: must knowfreq 30%

basics

~20 s

The ClassFileTransformer contract fails quietly: an exception from transform is swallowed and the class loads without that change, null means unchanged, names arrive slash-separated, and only classes defined after addTransformer pass through, so earlier ones need retransformClasses.

open as a page

On HotSpot, how does a Java agent started with -javaagent differ from a native JVMTI agent started with -agentlib or -agentpath, such as the JDWP debug agent?

level: middleimportance: should knowfreq 25%

basics

~20 s

A Java agent is a JAR whose code gets an Instrumentation handle, chiefly to transform class bytes; a native JVMTI agent is a C or C++ library using the JVM Tool Interface, with debugger events, heap walking and thread control.

open as a page

With java.lang.instrument, when should an agent call retransformClasses rather than redefineClasses on an already loaded class, and what must it enable for each?

level: middleimportance: should knowfreq 28%

basics

~10 s

retransformClasses reruns the retransform-capable transformers on a class's initial bytes, so an agent can add or remove its instrumentation; redefineClasses installs replacement bytes the caller supplies. They need Can-Retransform-Classes and Can-Redefine-Classes respectively.

open as a page

Your platform team ships an in-house Java agent into every JVM service; what do you require of that agent before it may load in production?

level: principalimportance: should knowfreq 15%

basics

~20 s

Require an agent that fails visibly and narrowly: transformers that catch and report every Throwable, an allowlist of classes it touches, only the manifest capabilities it uses, launch-time loading via -javaagent, a tested off-switch, relocated dependencies and per-JDK compatibility tests.

open as a page

A Java agent's transformer injects calls to the agent's own recorder class; instrumented application classes work, but an instrumented JDK class throws NoClassDefFoundError; why?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Classes from a Java agent JAR are defined by the system class loader, but JDK core classes are defined by the bootstrap loader, which cannot see them; the recorder must go on the bootstrap search via Boot-Class-Path or appendToBootstrapClassLoaderSearch.

open as a page