title: Use of instrumentation for size of objects
body: <p>I used the article <a href="http://www.devinline.com/2016/05/java-instrumentation-fundamental-part-1.html?m=1" rel="nofollow">http://www.devinline.com/2016/05/java-instrumentation-fundamental-part-1.html?m=1</a></p>
  
  <p>I need to get size of query results. </p>
  
  <p>But calling of </p>
  
  <pre><code>long sizeOfObject = InstrumentationAgent.findSizeOfObject(myvar);
  </code></pre>
  
  <p>returns the error</p>
  
  <blockquote>
    <p>Agent not initted.</p>
  </blockquote>
  
  <p>I have the main method of class with throws <code>Exception</code>
  Can you give a recommendation for right syntax?</p>
  
  <p>Rev:
  Agent code:</p>
  
  <pre><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);
          }
      }
  }
  </code></pre>
  
  <p>My invoking:</p>
  
  <pre><code>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();
  }
  </code></pre>