so, you’ve found java.lang.instrument.Instrumentation. neat, huh?
now, rather than having to start your agent via the command line, wouldn’t it be neat to do what they suggest in the package javadocs and load an agent dynamically at runtime?
i had a hell of a time finding details on exactly how to do this. install an agent in another vm? sure. current vm? nah.
in randomly following links last night, i came across a blog post from dain, and it mentioned a getPid() routine that OpenJPA uses. this tickled my memory, and i went looking for the class that uses it. i found the InstrumentationFactory from the OpenJPA code. jackpot!
what they do, is use the Attach API that Sun added in Java 6 to dynamically load an agent. They had to do a trick in order to figure out the current PID, but with that, no problem!
i did need to make some tweaks to their code to have it load in my environment. if you’re working in an environment with dynamic class loaders, when the class is loaded as an agent, it will be a new instance and thus not visible to the factory as-is. to get around this, split the factory into two pieces. the agent, and the factory. the factory does not use the agent at all, it always accesses it reflectively. then, after the agent has been loaded, use Class.forName("your.agent.class.name", true, ClassLoader.getSystemClassLoader() ) to get the instance. reflectively load the stored instrumentation and bingo!
June 30th, 2008 at 6:39 am
It was an interesting read to learn this stuff. I thought agents cannot be attached in runtime. What makes me wonder is the Attach API is available only in Java 6 while the instrumentation API is available in Java 5. They both should have been introduced in Java 5.
June 30th, 2008 at 9:31 am
Java 6 also added the ability to re-transform classes. given a java.lang.Class, you can then decide to re-process it. That’s very nice for any hierarchy-aware transformations, since you don’t need to re-invent isAssignableFrom/etc.
All in all, makes me wonder why I didn’t move to Java 6 earlier!
August 14th, 2008 at 6:15 pm
[...] public links >> java6 dynamically installing agents in java 6 First saved by shcheesman | 1 days [...]