2013-06-29
内存消耗测试
当一个Java应用程序运行时,有很多需要消耗内存的因素存在,如对象、加载类、线程等。在这里只考虑程序中的对象所消耗的虚拟机堆空间,这样我们就可以利用Runtime类的freeMemory()和totalMomery()方法。
public class Handler implements InvocationHandler {
private Object obj;
public Handler(Object obj) {
this.obj = obj;
}
public static Object newInstance(Object obj) {
Object result = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new Handler(obj));
return result;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
try {
Log.i(“Handler”, "begin method " + method.getName());
long start = Memory.used();
result = method.invoke(obj, args);
long end = Memory.used();
Log.i(“Handler”, "the method " + method.getName() + “ lasts ” + (end – start) + “ms”);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException(“unexpected invocation exception: ” + e.getMessage());
} finally {
Log.i(“Handler”, "end method " + method.getName());
}
}
}
public class Memory {
public static long used() {
long total = Runtime.getRuntime().totalMemory();
long free = Runtime.getRuntime().freeMemory();
return (total - free);
}
}