Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain instance of Instrumentation in Java

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.

like image 242
IAmYourFaja Avatar asked May 21 '12 20:05

IAmYourFaja


People also ask

What is instrumentation in Java?

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.

What is Premain method in Java?

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.

How do I create a Javaagent?

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.

What is bytecode instrumentation?

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.


1 Answers

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?

like image 65
Evgeni Sergeev Avatar answered Sep 21 '22 02:09

Evgeni Sergeev