Introduction

Java agents are a special type of class which, by using the Java Instrumentation API, can intercept applications running on the JVM, modifying their bytecode. Java agents aren’t a new piece of technology. On the contrary, they’ve existed since Java 5. But even after all of this time, many developers still have misconceptions about this feature—and others don’t even know about it.

Defining Java Agents

Java agents are part of the Java Instrumentation API. So to understand agents, we need to understand what instrumentation is.

Instrumentation, in the context of software, is a technique used to change an existing application, adding code to it. You can perform instrumentation both manually and automatically. You can also do it both at compiling time and runtime.

So, what is instrumentation good for? It’s meant to allow you to change code, altering its behavior, without actually having to edit its source code file. This can be extremely powerful and also dangerous. What you can do with that is left to you. The possibilities are endless. Aspect-Oriented Programming? Mutation testing? Profiling? You name it.

With that out of the way, let’s focus again on Java agents. What are these things, and how do they relate to instrumentation?

In short, a Java agent is nothing more than a normal Java class. The difference is that it has to follow some specific conventions. The first convention has to do with the entry point for the agent. The entry point consists of a method called “premain,” with the following signature:

public static void premain(String agentArgs, Instrumentation inst) If the agent class doesn’t have the “premain” method with the signature above, it should have the following, alternative method:

public static void premain(String agentArgs) As soon as the JVM initializes, it calls the premain method of every agent. After that, it calls the main method of the Java application as usual. Every premain method has to resume execution normally for the application to proceed to the startup phase.

The agent should have yet another method called “agentmain.” What follows are the two possible signatures for the method:

public static void agentmain(String agentArgs, Instrumentation inst) public static void agentmain(String agentArgs) Such methods are used when the agents are called not at JVM initialization, but after it.

Reference List

  1. https://stackify.com/what-are-java-agents-and-how-to-profile-with-them/