Java Agents are an interesting capability of the JVM. Agents can either be Static(Load when the java app starts with a special flag) or they can be Dynamic(using the dynamic API from java we can dynamically bind to a specific JVM PID. Agents can be used to run any code before the app starts or even to change the bytecode. The cool thing about agents is the fact that is a runtime thing and we do not need to change the source code of the target app. Agents are similar to Aspects but IMHO much better. Mockito uses mocks in order to test difficult scenarios, pretty much all observability solutions for logs and metrics also have agents. Today I want to share 2 pocs, one using a vanilla java app and doing bytecode manipulation, The second using Spring Boot 2.x and running code forever in a background thread as the app also runs. So Let’s get started!

The Video

The Code


Diego Pacheco

Originally published at on July 5, 2021.

Brazilian, Software Architect, SWE(Java, Scala, Rust, Go) SOA & DevOps expert, Author. Working with EKS/K8S. (Opinions on my own)