我具有由JavaSpecialists newsletter 調用出到類這種方法threadAllocatedBytes()ManagementFactory爲什麼getThreadAllocatedBytes不一致?
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import javax.management.ObjectName;
public class MemoryTest {
public static void main(String[] args) {
for (int i = 0; i < 10; ++i)
testMemory(i);
}
private static void testMemory(int nChars) {
long bytes = threadAllocatedBytes();
char[] test = new char[nChars];
long bytes2 = threadAllocatedBytes();
System.out.println("diff[" + +(nChars + 1) + "] = " + (bytes2 - bytes));
}
public static long threadAllocatedBytes() {
try {
return (Long) ManagementFactory.getPlatformMBeanServer().invoke(
new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME), "getThreadAllocatedBytes",
new Object[] { Thread.currentThread().getId() }, new String[] { long.class.getName() });
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
該程序的輸出是;
diff[1] = 1072
diff[2] = 1080
diff[3] = 1080
diff[4] = 1080
diff[5] = 1080
diff[6] = 1088
diff[7] = 1088
diff[8] = 28584
diff[9] = 1088
diff[10] = 1096
爲什麼第8次運行會顯示更高的分配? 我能做些什麼才能使它更加一致?
Interstingly如果測試運行具有不同尺寸的'炭[] test'例如'new char [nChars * 10]',...,'new char [nChars * 1000]',我堅持觀察到大約26-28kb的第8個分配的跳轉,與分配的內存無關。 – wero