我用了一篇文章http://www.devinline.com/2016/05/java-instrumentation-fundamental-part-1.html?m=1
我需要得到查询结果的大小。
但呼唤
long sizeOfObject = InstrumentationAgent.findSizeOfObject(myvar);返回错误
探员没有告密。
我有类的主要方法和抛出,Exception,你能给一个正确的语法建议吗?
代理代码:
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);
}
}
}我的请求:
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();
}发布于 2016-09-16 14:01:10
您要么忘记添加带有条目的META-INF/MANIFEST.MF
Premain-Class: org.h2.command.InstrumentationAgent或者在没有-javaagent:path/to/agent.jar的情况下运行应用程序。
这里您可以找到关于如何使用代理运行应用程序的完整工作示例。
您还可以在官方javadoc中找到有关清单条目和运行代理的更多信息。
注意事项
似乎您正在尝试获取ResultSet将返回的数据大小,而不是ResultSet对象本身消耗的内存量。问题是
size = InstrumentationAgent.findSizeOfObject(rs);这并不是最好的方法,因为ResultSet只维护对数据库行的游标,并且不存储所有结果。但是,您可以使用它获取所有数据,并使用findSizeOfObject汇总大小。但是你最后要知道的是,Instrumentation#getObjectSize可能会返回不准确的结果。
返回指定对象消耗的存储量的特定于实现的近似。结果可能包括部分或全部对象的开销,因此对于在实现中进行比较非常有用,而不是在实现之间进行比较。在JVM的单个调用过程中,估计值可能会发生变化。
https://stackoverflow.com/questions/39498765
复制相似问题