Video in progress
What is a Java agent, how do premain and agentmain work, and why does Java 21 warn about dynamically loaded agents?
An agent is a jar that can change the bytecode of classes, as they load or afterwards, through the Instrumentation API. With -javaagent, premain is called at startup; with attach, agentmain is called in an already running JVM. Since JDK 21, dynamic loading prints a warning because it can compromise the integrity of the JVM.
📖 Answer
The agent jar's manifest names Premain-Class and/or Agent-Class:
public class TimingAgent {
public static void premain(String args, Instrumentation inst) {
inst.addTransformer(new ClassFileTransformer() {
@Override
public byte[] transform(ClassLoader loader, String name, Class<?> cls,
ProtectionDomain pd, byte[] bytes) {
if (!name.startsWith("com/acme/")) return null; // we don't touch it
return Weaver.addTiming(bytes); // with ByteBuddy/ASM
}
});
}
}
At startup: java -javaagent:timing.jar -jar app.jar. The JVM calls premain before main, and then every class being loaded passes through the transformer.
For a running process, you connect with the Attach API (VirtualMachine.attach(pid).loadAgent(...)). Then agentmain is called, and already loaded classes can be rewritten with retransformClasses. Retransformation is limited: you can't add fields or methods, only method bodies change.
APM agents, Mockito (the inline mock maker), JaCoCo and async-profiler all work through this mechanism.
The change in JDK 21 (JEP 451): if an agent is loaded dynamically into a running JVM, a warning is printed. In the future this will be forbidden by default. The reason is "integrity by default": no library should be able to quietly attach and modify the JDK's internals. To allow it, use -XX:+EnableDynamicAgentLoading. A -javaagent given at startup is not affected.
In practice you hit this in tests: Mockito's older way loads itself as a dynamic agent. The fix is to pass Mockito as a -javaagent through the build tool.
Sign up to mark studied questions and save your progress.