2016-09-14 17 views
4

我使用了物品http://www.devinline.com/2016/05/java-instrumentation-fundamental-part-1.html?m=1使用儀器測量物體的大小

我需要獲取查詢結果的大小。

long sizeOfObject = InstrumentationAgent.findSizeOfObject(myvar); 

調用但是返回錯誤

代理不initted。

我有拋出類的主要方法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(); 
} 
+0

顯示您的'MANIFEST.MF'和代理商代碼 – vsminkov

+0

添加nessasary代碼 –

+0

任何人都可以幫忙嗎? –

回答

1

要麼你忘了與入門

Premain-Class: org.h2.command.InstrumentationAgent 

或運行你的應用程序添加META-INF/MANIFEST.MF沒有-javaagent:path/to/agent.jar

Here您可以找到完整的工作示例,說明如何使用代理運行啓動應用程序。

您還可以在official javadoc中找到關於清單條目和運行代理的更多信息。

注意

好像你正在試圖讓將由ResultSet返回而不是內存量ResultSet對象本身消耗數據的大小。問題是,

size = InstrumentationAgent.findSizeOfObject(rs); 

會不會因爲ResultSet僅保留光標到數據庫行,不存儲所有結果的最佳方法。但是,您可以使用它獲取所有數據並使用findSizeOfObject彙總尺寸。但最後一件你應該知道的是,Instrumentation#getObjectSize可能會返回不準確的結果

返回指定對象所消耗存儲量的特定於實現的近似值。結果可能包含部分或全部對象的開銷,因此對於實現中的比較而非實現之間的比較是有用的。估計值可能會在單個JVM調用期間發生變化。

相關問題