I am trying to write a simply ObjectUtils
class that contains a variety of utility methods for all Objects. I would like to have one of them called getObjectSize(Object)
where you pass it an instantiated Object and it returns the Object's size in memory:
public class ObjectUtils {
private static volatile Instrumentation instrumentation;
public static final long getObjectSize(final Object p_oToGauge)
{
return instrumentation.getObjectSize(p_oToGauge);
}
}
However, it seems that in order to obtain an implemented Instrumentation
instance, you need to do all sorts of fancy things with JRE agents and a so-called premain
method.
Is there an easy way to get access to the local JRE's Instrumentation
instances? I looked for something through the Runtime
API but could find nothing.
Instrumentation is the addition of byte-codes to methods for the purpose of gathering data to be utilized by tools. Since the changes are purely additive, these tools do not modify application state or behavior.
The premain is a mechanism associated with the java. lang. instrument package, used for loading "Agents" which make byte-code changes in Java programs. The mechanism is explained in the java.
To create a successful javaagent we'll need four things: an agent class, some meta-information to tell the JVM what capabilities to give to our agent class, a way to make the JVM load the . jar with the agent before it starts minding the application's business and a coffee.
Bytecode instrumentation is a process where new function- ality is added to a program by modifying the bytecode of a set of classes before they are loaded by the virtual machine. This paper will look into the details of bytecode instrumen- tation in Java: the tools, APIs and real-life applications.
I found a class called InstrumentationFactory
.
The first time someone asks for an instance of Instrumentation
, it creates an agent JAR file, then finds the PID of its own process and attaches it to the JVM inside that... Which calls its agentmain(..)
, giving it the Instrumentation
instance of interest.
I'm not sure how reliable that approach is. What I would try next is search the code of OpenJDK to see where and how an Instrumentation
instance is created. Perhaps, in the absence of security requirements, it would be possible (via reflection) to get that mechanism to furnish an Instrumentation
instance without having to attach or preload an agent?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With