import java.lang.instrument.Instrumentation;
public class ObjectSizeFetcher {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
public static void main(String[] args) {
// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
System.out.println( "---------------" );
System.out.println("heapSize >> "+humanReadableByteCount(heapSize,true));
System.out.println("heapMaxSize >> " + humanReadableByteCount(heapMaxSize,true));
System.out.println("heapFreeSize >> " + humanReadableByteCount(heapFreeSize,true));
}
/**
* see FileUtils.byteCountToDisplaySize(long size)
* @param bytes
* @param si
* @return
*/
public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
}
see
http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html
댓글 없음:
댓글 쓰기