1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import java.util.Arrays;
import java.util.Random;
public class MemoryTest {
public static void main(String[] argv) throws InterruptedException{
Random r = new Random();
for (int i=0; i<150;i++){
int size = (r.nextInt(50)+10)*1024*1024; //entre 10M et 60M
allocate(size);
long total = Runtime.getRuntime().totalMemory();
long free = Runtime.getRuntime().freeMemory();
Runtime.getRuntime().gc(); // essayez sans
displayMemory(free,total,Runtime.getRuntime().freeMemory(),Runtime.getRuntime().totalMemory());
}
}
public static void allocate(int size){
byte[] b = new byte[size];
Arrays.fill(b, (byte)69);
}
private static void displayMemory(long freeBefore, long totalBefore, long freeAfter,
long totalAfter) {
System.out.printf("before. Free: %04.2fM / %04.2fM (%04.2fM used)",((float)freeBefore)/(1024*1024),((float)totalBefore)/(1024*1024),((float)totalBefore-freeBefore)/(1024.0*1024));
System.out.printf("after. Free: %04.2fM / %04.2fM (%04.2fM used)\n",((float)freeAfter)/(1024*1024),((float)totalAfter)/(1024*1024),((float)totalAfter-freeAfter)/(1024.0*1024));
}
} |