The use of instruments for measuring the size of objects

I used the article http://www.devinline.com/2016/05/java-instrumentation-fundamental-part-1.html?m=1

I need to get the size of the query results.

But the challenge

long sizeOfObject = InstrumentationAgent.findSizeOfObject(myvar);

returns an error

Agent is not included.

I have a basic class method with throws. Exception Can you give recommendations on the correct syntax?

Rev: Agent Code:

package org.h2.command;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;

public class InstrumentationAgent {
    /*
     * System classloader after loading the Agent Class, invokes the premain
     * (premain is roughly equal to main method for normal Java classes)
     */
    private static volatile Instrumentation instrumentation;

    public static void premain(String agentArgs, Instrumentation instObj) {
        // instObj is handle passed by JVM
        instrumentation = instObj;
    }

    public static void agentmain(String agentArgs, Instrumentation instObj)
        throws ClassNotFoundException, UnmodifiableClassException {
    }

    public static long findSizeOfObject(Object obj) {
        // use instrumentation to find size of object obj
        if (instrumentation == null) {
            throw new IllegalStateException("Agent not initted");
        } else {
            return instrumentation.getObjectSize(obj);
        }
    }
}

My challenge:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import org.h2.command.InstrumentationAgent;
import static java.lang.System.out;  

public class CacheOptimize {
    public long Size;

    public static void main(String[] args) throws Exception {
        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:file:D:/server/h2/exp1.h2.db", "sa", "sa");
        Statement stat = conn.createStatement();

        ResultSet rs;
        rs = stat.executeQuery("select * from TAbles");
        Size = InstrumentationAgent.findSizeOfObject(rs);   
    }
    stat.close();
    conn.close();
}
+4
source share
1 answer

You either forgot to add META-INF/MANIFEST.MFwith the record

Premain-Class: org.h2.command.InstrumentationAgent

or run the application without -javaagent:path/to/agent.jar.

Here you can find a complete working example of how you can run your application using an agent.

javadoc.

, , ResultSet, , ResultSet. ,

size = InstrumentationAgent.findSizeOfObject(rs);

, ResultSet . , , findSizeOfObject. , , , Instrumentation#getObjectSize

, . , , , . JVM.

+1

Source: https://habr.com/ru/post/1654613/


All Articles