Hey Dev.to community! π
I'm Abhishek, a Java enthusiast diving deep into the JVM internals. I'm building vtracer β a low-overhead JVM agent for runtime tracing and virtual thread pinning detection.
This is Day 1 of my journey. Today, I built the foundation: a simple Java agent that loads and prints a message.
Let's dive in!
Why Java Agents? The Magic Behind the JVM
Java agents are powerful tools that let you instrument code at runtime using the Instrumentation API. They can modify bytecode, add logging, monitor performance, or even implement AOP β all without changing the original code.
Agents load in two ways:
-
Static:
-javaagentat startup - Dynamic: Attach to running JVM
Today, we focused on static attach β the basics.
Step-by-Step: My First Premain Agent
Maven Project Setup
Created a simple Maven project with Java 21.pom.xml with Agent Manifest
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<Premain-Class>com.example.vtracer.Agent</Premain-Class>
<Can-Redefine-Classes>true</Can-Redefine-Classes>
<Can-Retransform-Classes>true</Can-Retransform-Classes>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
- Agent Class
package com.example.vtracer;
import java.lang.instrument.Instrumentation;
public class Agent {
public static void premain(String agentArgs, Instrumentation inst) {
System.out.println("[vtracer] Agent loaded successfully via premain");
System.out.println("[vtracer] Instrumentation: " + inst);
System.out.println("[vtracer] Ready for instrumentation β Day 1 complete!");
}
}
- Build & Run
mvn clean package
java -javaagent:target/vtracer-1.0.jar TestApp
Output:
[vtracer] Agent loaded successfully via premain
[vtracer] Instrumentation instance: sun.instrument.InstrumentationImpl@...
[vtracer] Ready for instrumentation β Day 1 complete!
Test app running...
Test app finished
What I Learned Today
-
premainruns before main - Manifest entries are mandatory
- Instrumentation object gives power to transform classes
This is just the beginning β next, ByteBuddy for method timing!
What's Next?
Day 2: Method entry/exit timing with ByteBuddy.
Follow my journey on GitHub: https://github.com/abhishek-mule/vtracer
Star β if you're excited about JVM internals!
java #jvm #java21 #agents #bytecode
Thanks for reading! Let's build cool stuff together. π
β Abhishek Mule
(Comment below if you're building something similar!)


Top comments (0)