Java 使用仪器测量对象的大小
我用了这篇文章 我需要得到查询结果的大小 但呼唤Java 使用仪器测量对象的大小,java,Java,我用了这篇文章 我需要得到查询结果的大小 但呼唤 long sizeOfObject = InstrumentationAgent.findSizeOfObject(myvar); 返回错误 代理未初始化 我使用抛出异常 你能推荐正确的语法吗 修订版: 代理代码: package org.h2.command; import java.lang.instrument.Instrumentation; import java.lang.instrument.UnmodifiableClassEx
long sizeOfObject = InstrumentationAgent.findSizeOfObject(myvar);
返回错误
代理未初始化
我使用抛出异常
你能推荐正确的语法吗
修订版:
代理代码:
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();
}
您可能忘记添加带有条目的META-INF/MANIFEST.MF
Premain-Class: org.h2.command.InstrumentationAgent
或者在不使用-javaagent:path/to/agent.jar的情况下运行应用程序
您可以找到如何使用代理运行启动应用程序的完整工作示例
您还可以在中找到有关清单条目和运行代理的更多信息
注意
似乎您正在尝试获取ResultSet
返回的数据大小,而不是ResultSet
对象本身消耗的内存量。问题是
size = InstrumentationAgent.findSizeOfObject(rs);
将不是最好的方法,因为ResultSet
只维护指向数据库行的游标,而不存储所有结果。但是,您可以使用它获取所有数据,并使用findSizeOfObject
汇总大小。但最不应该知道的是,这可能会返回不准确的结果
返回指定对象消耗的存储量的特定于实现的近似值。结果可能包括对象的部分或全部开销,因此有助于在实现内进行比较,而不是在实现之间进行比较。在JVM的单个调用过程中,估计值可能会发生变化
显示您的MANIFEST.MF
和代理代码添加了Nessary codeCan Anywhere help?添加了一个解释错误的尝试和maven项目,该项目实现了您想要的功能