NOT YET FULLY IMPLEMENTED
๐ Learning and exploring how to instrument JVM programs using agents.
The JVM gives us a powerful dynamic runtime. As such, we can do things like load code dynamically at runtime or instrument already-compiled code with other code. We should be cautious when using these features. This project is me learning Java agents. What can we do with agents? How do you apply an agent to a program?
This project is designed with two Gradle subprojects:
program/
- This is a "hello world"-style program that knows nothing about agents. It is going to be instrumented by an agent.
agent/
- This is a Java agent. We are going to instrument
program
with this agent when we runprogram
.
- This is a Java agent. We are going to instrument
Follow these instructions to build an agent, build a program, and to run the program instrumented with the agent.
- Pre-requisite: Java 21
- Build the agent distribution
-
./gradlew agent:jar
- Agents are usually built and distributed as a
.jar
file. That's the case here. The agent was built toagent/build/libs/agent.jar
.
-
- Build the program distribution
-
./gradlew program:installDist
- The distribution is in
program/build/install/program/
. Pay attention to the "start script" fileprogram/build/install/program/bin/program
. This script is generated by Gradle's built-inapplication
plugin and the script provides extension points for us to customize the behavior. In particular, we'll use the environment variableJAVA_OPTS
to set the-javaagent
JVM option to instrument our program with our custom agent.
-
- Run the program in a way that also instruments it with the agent
-
JAVA_OPTS="-javaagent:$(pwd)/agent/build/libs/agent.jar" ./program/build/install/program/bin/program
- It will print something like the following.
-
Hello from the agent! The agent was able to find a class defined in the main program: 'dgroomes.program.Runner'. Hello from the main program! The main program was able to find a class defined in the agent: 'dgroomes.agent.Agent'.
-
General clean-ups, TODOs and things I wish to implement for this project:
- DONE Scaffold. Do not instrument anything yet.
- Instrument a class. I want to maybe just count invocations of a method.
- Bring in third-party libraries and do something interesting/realistic.
- JavaDoc for
java.lang.instrument
-
Provides services that allow Java programming language agents to instrument programs running on the Java Virtual Machine (JVM).
- This is required reading.
-