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?
answer
- JAR versus shared library
- Instrumentation versus jvmtiEnv
- javaagent rides on a native agent
- breakpoints, heap walking, events
- some capabilities only at start-up
basics
~20 sA 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.
solid answer
~50 s`-agentlib:name` loads a native library by name (`libname.so` on Linux) and `-agentpath` loads one from an absolute path; the JVM calls its `Agent_OnLoad`, or `Agent_OnAttach` when it is loaded into a running JVM, and the library uses JVMTI: breakpoints, single-stepping, method entry and exit events, local variables, heap iteration, thread suspension. The JDWP debug agent is one, started as `-agentlib:jdwp=...`. `-javaagent:agent.jar` is itself built on JVMTI: HotSpot turns it into the JDK's native `instrument` agent, which reads the manifest, creates the `Instrumentation` object and calls `premain`. A Java agent therefore gets a narrow, portable slice: class-file transformation, retransform and redefine, class-path appends and object sizes. A native agent is a platform-specific binary, and a crash in it takes the JVM down. In HotSpot, several event capabilities are offered only during start-up, so an agent loaded later usually cannot get them.
code
bash · 8 lines# native JVMTI agent by library name (libmyprof.so, JDK lib dir or library path)
java -agentlib:myprof=interval=10ms -jar app.jar
# native JVMTI agent by absolute path, no name expansion
java -agentpath:/opt/agents/libmyprof.so=interval=10ms -jar app.jar
# Java agent JAR (HotSpot loads it through the native 'instrument' agent)
java -javaagent:/opt/agents/metrics-agent.jar=com/acme/ -jar app.jargo deeper
Recall that the JVM accepts two kinds of agents: Java agents in a JAR via -javaagent, and native libraries via -agentlib or -agentpath, such as the debugger's JDWP agent.
Explain that -javaagent runs on the JDK's native instrument agent, what each kind's entry point is, and which powers JVMTI has that Instrumentation lacks.
Pick the right kind for a tool from what it must observe, and know that HotSpot withholds some event capabilities from agents loaded into a running JVM.
Weigh native agents' reach against their per-platform builds and crash risk inside every process, versus a Java agent's portability and narrower, bytecode-only view.
## Two kinds of agent The JVM Tool Interface (**JVMTI**) is the native programming interface HotSpot offers to tools such as debuggers, profilers, monitoring and coverage tools. A **native agent** is a shared library written in C or C++ that the JVM loads into its own process and that calls JVMTI directly. A **Java agent** is a JAR whose code receives a `java.lang.instrument.Instrumentation` object. The two are not unrelated: the Java agent mechanism is itself implemented by a native JVMTI agent that ships with the JDK. | | Java agent | Native JVMTI agent | |---|---|---| | Launch option | `-javaagent:<jar>[=<options>]` | `-agentlib:<name>[=<options>]` or `-agentpath:<path>[=<options>]` | | Written in | Java or another JVM language | C or C++ against the JVMTI header | | Entry point | `premain` or `agentmain` | `Agent_OnLoad` or `Agent_OnAttach` | | Gets | an `Instrumentation` object | a JVMTI environment with the capabilities it requests | | Main power | rewriting class bytes | events, thread and frame control, heap access, and class-byte hooks | | Portability | one JAR for every platform | one binary per operating system and CPU | | A bug | usually an exception, not a process crash | can crash the whole JVM process | ## How the JVM starts each 1. `-agentlib:foo=opts` names a library: HotSpot looks for the platform file name (`libfoo.so` on Linux) first in the JDK's own library directory, then on the platform library path. `-agentpath:/opt/agents/libfoo.so=opts` loads exactly that file, with no name expansion. 2. The JVM calls the library's `Agent_OnLoad` during start-up, before any application class runs. A native agent loaded into a running JVM gets `Agent_OnAttach` instead. 3. `-javaagent:agent.jar=opts` is turned by HotSpot into the JDK's native **`instrument`** agent with `agent.jar=opts` as its options, and the `java.instrument` module is added to the root modules. 4. The `instrument` agent opens the JAR, reads `Premain-Class` and the `Can-*` attributes, translates them into JVMTI capabilities, creates the `Instrumentation` object and, once the VM is initialised, calls `premain`. The JDWP debug agent behind remote debugging is a native agent of the first kind, started as `-agentlib:jdwp=...` from the JDK's own library directory. ## What only a native agent can do JVMTI exposes far more than class bytes: - **Breakpoints and single-stepping**, which is what a debugger needs. - **Method entry and exit, exception and field-access events**, delivered as callbacks into native code. - **Local variables and stack frames** of any thread, including popping a frame or forcing an early return. - **Heap walking and object tagging** through `IterateThroughHeap` and `FollowReferences`, which heap analysers use. - **Thread suspension, monitor information** and garbage-collection start and finish events. - **Class-byte hooks** through the `ClassFileLoadHook` event, so native agents can transform classes too. `Instrumentation` has no method for any of the first five. A Java agent can only approximate them by rewriting bytecode, for example by inserting calls at method entry, which changes the code it is measuring. ## What a Java agent gets instead The Java side is a deliberately small, portable slice: - `addTransformer` and `removeTransformer` for `ClassFileTransformer`s; - `retransformClasses` and `redefineClasses` for classes already loaded; - `appendToBootstrapClassLoaderSearch` and `appendToSystemClassLoaderSearch`; - `getAllLoadedClasses`, `getInitiatedClasses` and `getObjectSize`; - `setNativeMethodPrefix`, and `redefineModule` to add reads, exports, opens, uses and provides to a module. Java and native transformers share one pipeline. The `ClassFileTransformer` documentation fixes the order: retransformation-incapable Java transformers, then incapable native ones, then retransformation-capable Java ones, then capable native ones. ## Start-up versus a running JVM Timing matters for capabilities. In HotSpot, some JVMTI capabilities are offered only while agents start with the JVM, the **OnLoad phase**: method entry and exit events, single-step, breakpoint, field-access and exception events, and access to local variables are among them. A native agent loaded into a running JVM normally cannot add those, unless an agent started at launch already acquired them. Redefinition and retransformation, by contrast, stay available in a running JVM, which is why a Java agent loaded late can still retransform classes. ## Choosing between them - Choose a **Java agent** to change what classes do, such as timing, tracing, coverage probes or mocks; it is portable, memory-safe and easy to ship. - Choose a **native agent** when the tool must observe the JVM itself: debugger control, heap inspection or low-level events. - Expect a native agent to be built and tested per platform, and treat its crashes as JVM crashes.
- Can a native JVMTI agent rewrite class bytes the way a ClassFileTransformer does?Yes. It enables the `ClassFileLoadHook` event and returns new bytes from the callback. Java transformers are in fact called from the same hook by the JDK's `instrument` agent. When both kinds are present, retransformation-incapable Java transformers run first, then incapable native ones, then capable Java ones, then capable native ones.
- Why can a native agent loaded into a running HotSpot JVM fail to get method entry events it gets at launch?HotSpot offers some JVMTI capabilities, including method entry and exit, single-step, breakpoint and local-variable access, only during the OnLoad phase at start-up. An agent attached later asks for them and gets `JVMTI_ERROR_NOT_AVAILABLE`, unless an agent started at launch already acquired them. Retransform and redefine capabilities remain available later.
- A Java agent bypasses JVMTI entirely; only native agents use it.
- A Java agent can set breakpoints and read local variables through Instrumentation.
- -agentlib takes the full file path of the agent library.
- A crash inside a native agent surfaces as a catchable Java exception.
- An agent loaded into a running JVM can acquire every JVMTI capability a launch-time agent can.