我有一个来自JavaSpecialists newsletter的方法threadAllocatedBytes(),它调用了ManagementFactory类。
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次运行显示分配更高?我该怎么做才能使它更加一致?