skip to content

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%

answer

  1. where the new bytes come from
  2. initial bytes, replayed transformers
  3. caller-supplied ClassDefinition
  4. two Can-* manifest flags
  5. isModifiableClass first

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.

solid answer

~40 s

Use `retransformClasses(Class...)` when the agent wants to instrument, or stop instrumenting, classes that are already loaded: the JVM starts from the class's initial bytes, reuses the saved output of retransform-incapable transformers, calls every transformer added with `addTransformer(t, true)`, and installs the result. Use `redefineClasses(ClassDefinition...)` to swap in bytes you supply without reference to the existing ones, as fix-and-continue debugging does. Each needs its manifest flag, `Can-Retransform-Classes: true` or `Can-Redefine-Classes: true`, visible through `isRetransformClassesSupported()` or `isRedefineClassesSupported()`, and each target must pass `isModifiableClass`: primitive and array classes never do, and HotSpot also refuses hidden classes. Both are all-or-nothing, run no static initializers, keep static values and leave running frames on the old code. The JVM accepts only a restricted set of changes and rejects the rest with `UnsupportedOperationException`.

code

java · 14 lines
java
static void instrumentLoaded(Instrumentation inst, ClassFileTransformer t, String prefix)
        throws UnmodifiableClassException {
    if (!inst.isRetransformClassesSupported()) {
        throw new IllegalStateException("agent JAR lacks Can-Retransform-Classes: true");
    }
    inst.addTransformer(t, true);                 // retransform-capable
    List<Class<?>> targets = new ArrayList<>();
    for (Class<?> c : inst.getAllLoadedClasses()) {
        if (c.getName().startsWith(prefix) && inst.isModifiableClass(c)) {
            targets.add(c);
        }
    }
    inst.retransformClasses(targets.toArray(new Class<?>[0])); // empty array: no-op
}

go deeper

for a junior

Recall that an agent can change classes that are already loaded, not only classes as they load, and that this ability has to be enabled.

for a middle

Explain where each call's bytes come from, which transformers run, the two Can-* attributes, and what isModifiableClass rules out.

for a senior

Use retransformation to instrument and later un-instrument a live service, knowing running frames, statics and instances are left as they were.

for a principal

Ask whether your agent needs redefinition at all; requesting only retransformation keeps its manifest's capabilities as narrow as its job.

## Two ways to change a loaded class `java.lang.instrument.Instrumentation` offers two operations on classes the JVM has already loaded. Both are optional JVM capabilities, both take a set of classes so interdependent changes can be made together, and both end in the same JVMTI machinery. They differ in where the new bytes come from. | | `retransformClasses(Class<?>...)` | `redefineClasses(ClassDefinition...)` | |---|---|---| | Input bytes | the class's initial bytes, rebuilt by the JVM | bytes the caller supplies in a `ClassDefinition` | | Transformers called | only retransform-capable ones; incapable ones' last output is reused | every registered transformer | | Intended use | adding, changing or removing instrumentation | replacing a class outright, as in fix-and-continue debugging | | Manifest attribute | `Can-Retransform-Classes: true` | `Can-Redefine-Classes: true` | | Support check | `isRetransformClassesSupported()` | `isRedefineClassesSupported()` | The JDK documentation draws the line itself: where the existing class bytes are to be transformed, as in bytecode instrumentation, `retransformClasses` should be used. ## How retransformation rebuilds a class 1. The JVM starts from the **initial class file bytes**, those passed to `ClassLoader.defineClass` or to the last `redefineClasses`. They are reconstructed, so the constant pool may be laid out differently, but the constant-pool indices used by method bytecode still correspond. 2. For every transformer added with `canRetransform` false, it reuses the bytes that transformer returned during the last load or redefinition, without calling it. 3. It calls `transform` on every transformer added with `addTransformer(t, true)`, in registration order, with `classBeingRedefined` set to the class. 4. It checks, verifies and installs the result as the class's new definition. Two consequences follow. Instrumentation does not stack up, since each retransformation starts again from the initial bytes. And removing a retransform-capable transformer with `removeTransformer`, then retransforming, rebuilds the class without that transformer's changes: this is how an agent takes its instrumentation back out. A retransform-incapable transformer's changes cannot be taken out this way, because its saved output is reused on every retransformation. ## How redefinition works `redefineClasses` takes pairs of a class and a replacement class file, built as `new ClassDefinition(theClass, bytes)`. The documentation describes it as replacing a class's definition without reference to the existing class file bytes, the way a tool does after recompiling from source. The supplied bytes become the input to the transformer chain, so every registered transformer, capable or not, still runs on them, with `classBeingRedefined` set, and an agent's instrumentation is reapplied on top of the replacement. Later retransformations start from these bytes rather than the original ones: after a redefinition, the redefined class file is the new baseline. ## A worked case A platform team must add its metrics agent to a service that cannot be restarted. The agent JAR declares `Agent-Class` and `Can-Retransform-Classes: true`, and no other capability. Its `agentmain` registers the transformer with `addTransformer(t, true)`, selects the loaded classes in the service's packages that pass `isModifiableClass`, and retransforms them in one call. If the team later wants the timing gone, the same agent removes the transformer and retransforms the same classes, and they return to their initial bytes. At no point does the agent need `Can-Redefine-Classes`, because it never supplies a class file of its own. ## Preconditions shared by both - The agent JAR's manifest must enable the matching capability; it is off by default, and any value other than `true` counts as false. - `addTransformer(t, true)` throws `UnsupportedOperationException` when retransformation is not supported. - Every target must pass `isModifiableClass`. Primitive classes and array classes never do, and HotSpot also refuses hidden classes. - An unmodifiable target makes the call throw `UnmodifiableClassException`. - The JVM accepts only a restricted set of changes to an existing class. Bytes that go beyond it are rejected with `UnsupportedOperationException`, and malformed ones with errors such as `ClassFormatError`. ## What both leave alone - **Running frames**: a method with active frames keeps executing its old bytecode, and new invocations use the new one. - **Static state**: no static initializer runs again, and static fields keep their values. - **Instances**: existing objects of the class are not affected. - **Atomicity**: if the call throws, none of the classes in the set has been changed. ## Choosing between them - An agent loaded into a running JVM that must instrument classes already in use calls `retransformClasses`: register a retransform-capable transformer, pick targets with `getAllLoadedClasses` and `isModifiableClass`, and retransform them. - An agent that wants its instrumentation removed again, and registered its transformer as retransform-capable, calls `removeTransformer` and then `retransformClasses` on the classes it touched. - `redefineClasses` fits only when the caller really holds a replacement class file, and every registered transformer still runs on it.

  • How does an agent remove its instrumentation from loaded classes without a restart?
    If `t` was registered retransform-capable, it calls `removeTransformer(t)` and then `retransformClasses` on the classes it changed. The JVM rebuilds each class from its initial bytes and applies only the transformers still registered. Frames already executing finish on the old code, and because class loading is concurrent, the removed transformer may still receive a few calls.
  • Does redefineClasses bypass the registered transformers?
    No. The bytes in each `ClassDefinition` are the input to the normal transformer chain, so retransform-capable and incapable transformers both run on them. An agent's instrumentation is therefore reapplied on top of a replacement class, and a later retransformation starts from the redefined bytes.

  • retransformClasses runs the transformers on the class's current, already instrumented bytes.
  • redefineClasses is the API meant for instrumenting a loaded class's existing bytes.
  • Retransforming a class runs its static initializer again.
  • Methods already executing switch to the new bytecode immediately.
  • Any loaded class, array classes included, can be retransformed.