Agente Java para conocer el tamaño de un objeto

Seguro que alguna vez habéis necesitado conocer el tamaño de un objeto en un programa Java…

Hasta ahora me había servido con el conocimiento extraído de la lectura de este artículo:

http://www.javaworld.com/javaworld/javatips/jw-javatip130.html

Pero esta vez necesitaba algo más preciso y configurable, necesitaba conocer el tamaño de un objeto concreto.

Googleando (sí, yo uso el Google para buscar, aunque eso sí con el Opera) he visto que la clase Instrumentation tiene un getObjectSize:

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize(java.lang.Object)

pero para poder usar esta clase es necesario que esté en un agente (cargado con la opción –javaagent)

El Agente sería este:

import java.lang.instrument.Instrumentation;

public class MyBasicProfiler {

private static Instrumentation instrumentation;

public static void premain(String args, Instrumentation inst) {

instrumentation = inst;

}

public static Long getSizeInBytes(Object o) {

if (o == null)

return null;

return new Long(instrumentation.getObjectSize(o));

}

public static String getSize(Object o) {

try {

if (o == null)

return «Referencia nula»;

long size = instrumentation.getObjectSize(o);

if (size < 1024)

return size + » Kbytes»;

return size / 1024 + » Mbytes»;

} catch (Throwable e) {

error(e);

return «Tamaño desconocido»;

}

}

public static String getHeapSize() {

return Runtime.getRuntime().totalMemory()/1024 + » Kbytes»;

}

public static String getHeapMaxSize() {

return Runtime.getRuntime().maxMemory()/1024 + » Kbytes»;

}

public static String getHeapFreeSize() {

return Runtime.getRuntime().freeMemory()/1024 + » Kbytes»;

}

public static String getUsedMemory() {

return (Runtime.getRuntime().totalMemory() – Runtime.getRuntime().freeMemory())/1024 + » Kbytes»;

}

public static void invokeGarbageCollector() {

try {

System.gc();

Thread.currentThread().sleep(100);

System.runFinalization();

Thread.currentThread().sleep(100);

} catch (InterruptedException e) {

error(e);

}

}

private static boolean firstTime = true;

private static void error(Throwable e) {

if (firstTime) {

System.err.println(«***********************»);

System.err.println(«Error al inicializar Agente»);

e.printStackTrace();

System.err.println(«***********************»);

firstTime=false;

}

}

}

El Agente debe estar dentro de un JAR

en cuyo MANIFEST.MF (carpeta META-INF/MANIFEST.MF) irá:

MANIFEST.MF:

Premain-Class: MyBasicProfiler

La forma de usarlo es muy sencilla:

public class TestBasicProfiler {

public static void main(String[] args) {

TestBasicProfiler test = new TestBasicProfiler();

System.out.println(«Memoria usada al comienzo:»+MyBasicProfiler.getUsedMemory());

Object object = new Object();

Integer i = new Integer(10);

Long l = new Long(10L);

String s = new String(«Cadena de texto»);

System.out.println(«Tamaño s antes for:»+MyBasicProfiler.getSize(s));

System.out.println(«Tamaño Clase antes for:»+MyBasicProfiler.getSize(test));

System.out.println(«Memoria usada al inicializar:»+MyBasicProfiler.getUsedMemory());

for (int j = 0; j < 1000; j++) {

s = s+ «_»+j;

}

System.out.println(«Tamaño s tras for:»+MyBasicProfiler.getSize(s));

System.out.println(«Tamaño Clase tras for:»+MyBasicProfiler.getSize(test));

System.out.println(«Memoria usada tras for:»+MyBasicProfiler.getUsedMemory());

MyBasicProfiler.invokeGarbageCollector();

System.out.println(«Memoria usada tras Garbage Collector:»+MyBasicProfiler.getUsedMemory());

}

}

Como se ve el Agente permite:

– Ver la memoria usada:

– Conocer el tamaño de un objeto:

– Invocar el Garbage Collector.

Para poder ejecutar el Test en el java de arranque de este debo cargar el Agente.

Por ejemplo en Eclipse pondría el JAR del Agente en la carpeta del proyecto Eclipse y en su configuración::

Respuesta

  1. […] queréis conocer cómo hacer un agente que haga esto mismo que haga esto podéis leer este post. GA_googleAddAttr("AdOpt", "1"); GA_googleAddAttr("Origin", "other"); […]

Replica a java.SizeOf: conocer tamañi « Java Mania Cancelar la respuesta