Java agents are a little-known but extremely powerful part of the Java ecosystem. Agents are able to transform existing classes at runtime, allowing scenarios such as logging and monitoring, hot reload or gathering code coverage. However, their usage presents a number of pitfalls as well. In this talk we will present the steps of writing a java agent from scratch, indicate various common mistakes and pain points and draw conclusions on best practices. Special care will be taken to discuss how running in an OSGi environment affects Java agents and how we can best approach integration testing in a modular environment. After this talk participants will have a better understanding of the Java instrumentation API, how it fits in with OSGi runtimes and about should / should not be done with it.
23. Packagingchallenges
Java agents...
must be packaged as a Jar file, with a specific
manifest
not trivially attached to the current process
usually a one-way deal, no support for rolling
back class changes
23
24. Customtestlaunchers
"unit" tests
launch Java process with custom agents attached
require separate communication channel with
java agent
no out-of-the-box support for code coverage and
other tools
24
25. Bootstrappingthetest
// 1. which java?
String javaHome = System.getProperty("java.home");
Path javaExe = Paths.get(javaHome, "bin", "java");
// 2. which jar?
String ja = findAgentJar();
// 3. which classpath?
String classPath = buildClassPath();
// 4. launch
ProcessBuilder pb = new ProcessBuilder(
javaExe.toString(), "-javaagent:" + ja,
"-cp", classPath,
TestApplication.class.getName()
);
25