JVMTI Agents: Native Access to the JVM
Learn how JVMTI agents register events, request capabilities, and collect JVM data while managing callback cost, native memory, and compatibility.
Learn how JVMTI agents register events, request capabilities, and collect JVM data while managing callback cost, native memory, and compatibility.
JVMTI Agents: Native Access to the JVM
The Java Virtual Machine Tool Interface (JVMTI) is a native interface for tools that need to inspect or control a running JVM. An agent can receive runtime events and call functions to inspect threads, classes, stacks, and heap references. The native library runs in the same process as the JVM, so a bug in the agent can affect the application directly.
JVMTI is one part of Java diagnostics, not the plumbing behind every tool. Java Flight Recorder (JFR) records JVM and application events through its own API, while Java Management Extensions (JMX) exposes management interfaces and metrics. Some tools use JVMTI, some use these higher-level APIs, and some use operating-system facilities. Check a tool’s own documentation before assuming how it collects data.
This guide uses the JVMTI 27 specification as its reference point. JVMTI support, optional capabilities, dynamic agent loading, and native library formats vary by JVM implementation, release, operating system, and CPU architecture. Confirm the target runtime before building or deploying an agent.
When to Use JVMTI
JVMTI is useful when a tool needs low-level runtime access that a higher-level interface does not expose. Examples include debugger features, targeted bytecode instrumentation, heap inspection, and custom runtime diagnostics. The interface is native and detailed, so use JFR, JMX, the Java instrumentation API, or an operating-system profiler when one already provides the data you need.
Method-entry and method-exit events deserve special caution. The JVMTI specification says enabling either can significantly degrade performance on many platforms and advises against them for performance-critical profiling. Allocation sampling is available through a separate API, but its cost still depends on the interval, runtime, and workload.
Architecture
An agent is a native library loaded into the JVM process. It receives a jvmtiEnv* environment through GetEnv, registers callback functions, requests capabilities, and enables selected events. Multiple agents can have separate JVMTI environments, but they still share the same process and can affect one another and the application.
Callbacks are not all delivered under one universal timing or thread rule. They are usually called on an application thread, often the thread that caused the event, but each event documents its own phase, callback restrictions, and arguments. JVMTI does not queue events for the agent, and callbacks must be re-entrant. JNI references and pointers passed to a callback may stop being valid when that callback returns, unless the event says otherwise.
Keep callback work short and bounded. Avoid file or network I/O, unbounded allocation, and assumptions that another callback cannot arrive concurrently. If the agent hands work to another thread, copy the data it needs while it is valid and define what happens when the queue is full. Track dropped records or apply a measured backpressure policy outside the callback.
graph TB
subgraph "JVM Process"
JVM[JVM Runtime]
subgraph "JVMTI Environment"
ENV[Capabilities and Functions]
CALLBACKS[Registered Callbacks]
end
AGENT[Native Agent Library]
WORKER[Optional Agent Worker]
end
JVM -->|Enabled events| CALLBACKS
CALLBACKS -->|Copy bounded data| WORKER
AGENT --> ENV
ENV --> JVM
Agent Lifecycle
Agents can load during JVM startup or, when the implementation supports it, attach to a running JVM:
Agent_OnLoadruns during the VM’s earlyOnLoadphase after startup with-agentlibor-agentpath. Some capabilities are only available in this phase. Many JVM functions are restricted until initialization completes.Agent_OnAttachruns in the live phase when a VM-specific attach mechanism loads the agent. The set of capabilities available at this point may be smaller.Agent_OnUnloadis the native agent’s shutdown entry point. It is useful for ordinary cleanup, but it cannot provide a guarantee that cleanup runs after a crash or forced process termination.
The usual setup is to obtain the JVMTI environment with GetEnv, request the capabilities the agent needs, register callbacks with SetEventCallbacks, and enable each event with SetEventNotificationMode. An event needs a callback and must be enabled; events that require a capability also need that capability granted. Check function return codes and query the granted capabilities rather than assuming every request succeeded.
Capabilities
Capabilities unlock optional functions or events. Not every VM implements every optional capability, and some capabilities are available only in particular phases. Use GetPotentialCapabilities to learn what the VM can offer, request only what the agent needs with AddCapabilities, then confirm the result with GetCapabilities.
| Capability | Enables | Practical note |
|---|---|---|
can_tag_objects |
Tags used to identify objects during heap operations and ObjectFree events |
Tags are metadata maintained by the VM; use them only when object identity is needed. |
can_generate_method_entry_events |
MethodEntry notifications |
The specification warns these can significantly degrade performance on many platforms. |
can_generate_method_exit_events |
MethodExit notifications |
The same performance warning applies; benchmark before enabling. |
can_generate_single_step_events |
Single-step debugger events | This can produce frequent callbacks; enable only for a focused debugging session. |
can_generate_sampled_object_alloc_events |
SampledObjectAlloc and SetHeapSamplingInterval |
Optional functionality; support and cost vary by VM and sampling interval. |
can_redefine_classes |
Class redefinition functions | Check the exact JVMTI limits and runtime support before depending on redefinition. |
Capabilities do not enable events by themselves. An event that needs a capability still needs a registered callback and an enabled notification.
Allocation Sampling
JVMTI 27 defines SampledObjectAlloc as a sampled allocation event. An agent requests can_generate_sampled_object_alloc_events, sets an average byte interval with SetHeapSamplingInterval, registers the event callback, and enables the event. The VM keeps a byte counter per thread and emits samples statistically around the selected interval; it is not a promise to report every allocation or to sample at a fixed time interval.
The interval is a tuning input, not an overhead guarantee. The specification notes that overhead is correlated with the interval, so compare several settings against an agent-free baseline under the same workload. Keep the callback small: copy the fields needed for analysis into bounded storage, then process or write them on an agent worker thread. Handle unsupported capability requests and failures from JVMTI functions explicitly.
VMObjectAlloc and ObjectFree are different events. VMObjectAlloc reports allocations when enabled and supported; it is not the sampled allocation API. ObjectFree reports only objects that were tagged, and its callback cannot use JNI functions or most JVMTI functions. Do not use ObjectFree as a substitute for recording allocation sites.
Measuring Agent Cost
Avoid fixed overhead claims such as “this agent costs 2%.” Results depend on the event, event rate, callback body, JVM build, hardware, and workload. Establish an agent-free baseline, then run the same representative workload with one event or capability enabled at a time. Compare throughput, CPU use, latency percentiles, allocation rate, and queue growth across repeated runs. Test the actual production JVM build and operating system, and include the cost of exporting or storing data.
For method-entry or method-exit instrumentation, the JVMTI specification’s performance warning is a reason to test an alternative first. For sampled allocation events, vary the sampling interval and measure the effect. For heap operations, measure pause time, CPU use, and temporary memory on a representative heap. Do not extrapolate from a small local run to a different production workload.
| Option | Interface and deployment | How to evaluate it |
|---|---|---|
| JVMTI agent | Native library using JVMTI functions and callbacks; often loaded with -agentpath |
Check each event’s phase and callback rules, then benchmark the exact event set. |
| Java instrumentation agent | Java agent using java.lang.instrument to transform classes |
Measure transformation scope and runtime effect on the application. |
| JFR | JVM flight recording with JVM and application events | Select the recording configuration and event set that answer the diagnostic question. |
| JMX | Java management interfaces, often exposed through platform MBeans | Check which metrics and operations are available and secure any remote connection. |
These options can coexist. A profiler or monitoring product may combine multiple APIs, so consult its documentation for the specific runtime and version.
Operational and Security Considerations
A native agent executes inside the JVM process under that process’s operating-system identity. Native code can access process memory and resources, and memory-safety bugs can corrupt or terminate the JVM. Treat an agent library as executable code: restrict who can provide startup options or attach to the process, protect the library and its configuration, and review its source and build provenance. A signature can help verify origin and integrity; it does not make the code safe.
Attaching is also a deployment choice. Support and policy are implementation-specific. On HotSpot, -XX:+DisableAttachMechanism disables the attach mechanism; this also removes attach-based diagnostics such as jcmd, jstack, jmap, and jinfo. Weigh that operational cost before using the flag as a control.
Plan compatibility explicitly. Build for the target operating system and architecture, check the target VM’s JVMTI version and granted capabilities, and test startup and attach paths separately. Retest after changing JDK vendor, major release, native toolchain, or agent version. Multiple agents share the JVM and may interfere with one another, so validate the full deployed combination.
Native Memory and JNI References
Use Deallocate for buffers returned by JVMTI functions, including memory requested with JVMTI’s Allocate. The agent may use malloc/free for memory it allocates itself, as long as it pairs allocators correctly; JVMTI does not require replacing the C allocator for all agent memory.
JNI object references passed to callbacks are generally local references and become invalid when the callback returns. Create a global reference only when the agent must retain an object, then release it with DeleteGlobalRef. A callback that makes JNI calls must also handle pending exceptions carefully. Prefer copying stable identifiers or primitive data over retaining Java objects.
Common Failure Modes
Method callbacks distort the workload
Symptom: Enabling method-entry or method-exit notifications changes throughput or latency enough to invalidate the measurement.
Response: Start with a baseline and enable one event at a time. The JVMTI specification warns that method entry and exit can significantly degrade performance on many platforms. Narrow the instrumentation scope or use another interface suited to the measurement.
Callback work backs up
Symptom: A callback performs formatting or I/O inline, or an asynchronous queue grows without bound.
Response: Keep callback work bounded, copy only the required data, and define a queue capacity and overflow policy. Measure callback latency and dropped records under load.
A capability is unavailable
Symptom: An agent works on one VM or phase but fails to enable an event elsewhere.
Response: Check the VM’s potential and granted capabilities, inspect every JVMTI error code, and report unsupported requirements clearly. Test the exact vendor, version, and load phase used in deployment.
Heap analysis affects the service
Symptom: A heap traversal changes pause time, CPU use, or memory pressure.
Response: Measure the operation on a representative heap. Select the JVMTI heap function that matches the question, such as IterateThroughHeap for heap iteration or FollowReferences for a reachability traversal, and avoid retaining callback data unnecessarily.
Observability Checklist
- Decide whether JVMTI is needed or whether JFR, JMX, Java instrumentation, or an OS tool is enough.
- Record the JDK vendor, build, JVMTI version, operating system, and CPU architecture.
- Check potential and granted capabilities; handle unsupported requests and error codes.
- Read the specific event’s phase, callback-safety, thread, and argument-lifetime rules.
- Keep callbacks short and re-entrant; define what happens when a queue fills.
- Benchmark the agent against a baseline with the production event set and workload.
- Restrict startup and attach access, and treat the native library as executable code.
- Check the operational impact before disabling the Attach mechanism.
Interview Questions
JVMTI is a native interface for inspecting and controlling a JVM. JFR records JVM and application events, while JMX provides Java management interfaces. They serve different purposes and are not all built on JVMTI. Choose the interface that exposes the data and controls a tool needs.
The VM passes a JavaVM* to the agent's startup entry point. The agent calls GetEnv with a supported JVMTI version to obtain a jvmtiEnv*, then checks the return code before using the interface.
Agent_OnLoad runs during startup in the OnLoad phase, commonly when the launcher uses -agentlib or -agentpath. Agent_OnAttach runs in the live phase when the VM supports dynamic attachment. The phase affects which functions and capabilities are available.
Request any capability the event requires, register its function in SetEventCallbacks, and enable it with SetEventNotificationMode. Check each function's result and verify that the VM granted the capability.
No. Delivery phase, thread, and callback restrictions are event-specific. Read the event's JVMTI specification entry; do not assume a rule documented for one event applies to the others.
JVMTI does not queue events, and callbacks may be delivered on application threads. The specification requires callbacks to be re-entrant. Keep their work bounded, avoid blocking I/O, and copy data before callback-scoped references or pointers expire.
They can generate a callback for each Java method entry or exit. The JVMTI specification warns that enabling them can significantly degrade performance on many platforms and advises against them for performance-critical profiling. Measure the exact workload or choose a different instrumentation approach.
SampledObjectAlloc uses the optional heap-sampling capability and a byte-based average interval set with SetHeapSamplingInterval. VMObjectAlloc is a separate allocation event. Do not treat the latter as a sampled event or assume either event has a fixed overhead.
ObjectFree is sent only for objects that were tagged. Its callback receives the tag, cannot call JNI functions, and can call only a limited set of JVMTI functions. It does not report allocation sites by itself.
Use GetPotentialCapabilities to inspect what the VM can offer, then request only the capabilities needed with AddCapabilities. Check the result and use GetCapabilities to confirm what was granted. Availability can depend on the VM and phase.
Compare an agent-free baseline with the same representative workload and runtime configuration. Enable one event or capability at a time, repeat the run, and compare throughput, latency, CPU use, allocation, and any data-queue growth. Results are specific to the event, JVM, hardware, and workload.
Copy only the information needed while the callback's pointers and local references are valid. If processing is deferred, enqueue the copy in bounded storage and choose an overflow policy, such as counting and dropping records. Do not write files or send network data inline from a hot callback.
Use Deallocate for memory returned by JVMTI functions, including memory obtained with JVMTI's Allocate. The agent may use malloc and free for its own allocations when it pairs them correctly. Do not free memory with a different allocator from the one that allocated it.
References passed by many JVMTI events are JNI local references and become invalid when the callback returns. Create a global reference only if the agent needs to retain an object, then release it with DeleteGlobalRef. Prefer copying primitive data or stable identifiers when possible.
IterateThroughHeap supports heap iteration, while FollowReferences traverses references reachable from a selected object or heap roots. Choose based on the question and read the function's callback and phase restrictions. Measure pause time and memory effects on a representative heap.
With can_tag_objects, an agent can associate a jlong tag with an object and use it during supported heap operations. Tags can also identify which objects may produce ObjectFree events. Use them when identity tracking is required and account for the work and storage your analysis needs.
JVMTI is a native interface for VM events and operations. A Java instrumentation agent uses the java.lang.instrument API, commonly to transform class files. They expose different hooks and have different deployment and compatibility costs; neither is universally the better choice.
On HotSpot, -XX:+DisableAttachMechanism prevents tools from attaching to the JVM. It also disables attach-based diagnostic tools such as jcmd, jstack, jmap, and jinfo. Check the target JVM's documentation and operational needs before using it.
JVMTI may not be available in every VM, optional capabilities may be missing, and dynamic attachment is implementation-specific. Native binaries also depend on the target operating system and architecture. Test the vendor, release, phase, and platform combination used in deployment.
A native agent runs inside the JVM process and under its operating-system identity. Its code can access process resources, and memory-safety bugs can corrupt or terminate the VM. Restrict who can load agents and review the library as executable code; a signature can establish origin, but it does not prove the code is safe.
Further Reading
- Advanced Java & JVM Internals Roadmap — Parent roadmap covering JVM internals
- JVMTI Heap Walking — Heap iteration and reference traversal
- JVMTI Specification, version 27 — Events, functions, capabilities, and agent lifecycle
- Java SE Monitoring and Management — JMX overview
- Flight Recorder API Guide — JFR recording and analysis APIs
- The
javacommand reference — HotSpot serviceability options, including Attach controls
Conclusion
JVMTI gives native tools detailed access to a JVM, with the responsibility that comes with running code in the application’s process. Check each event’s rules, request only supported capabilities, keep callbacks bounded, and measure the agent on the target runtime. For many diagnostics tasks, JFR or JMX already offers the needed view with a simpler interface.
Category
Related Posts
Crash Dump Analysis: HsErr Files, Core Dumps, SIGSEGV
Read HotSpot fatal error logs, handle JNI references safely, and check Linux core-dump configuration before analyzing with GDB.
Deoptimization Debugging: When JIT Compiled Code Reverts
Learn what causes the JVM to deoptimize JIT-compiled code, how to detect deoptimization events, and how to fix the underlying issues.
Java Flight Recorder: Continuous Monitoring and Diagnostics
Learn Java Flight Recorder setup, storage limits, overhead measurement, and practical analysis with Oracle JDK 25 and JMC 9.1.2.