import java.util.Random;
public class S {
Object[] c = new Object[10];
int length = 0;
// public Object pop() {
// if (length == 0)
// return null;
// Object r = c[--length];
// c[length] = null;
// return r;
// }
public Object pop() {
if (length == 0)
return null;
return c[--length];
}
public int push(Object o) throws Exception{
if (length >= 10)
throw new Exception("Stack is full.");
c[length++] = o;
return length;
}
public static void main(String[] args) throws Exception {
S s = new S();
Random r = new Random();
for (int i = 0; i < 1000000000; i++) {
s.push(r.nextInt(1000000000)
+ "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");
s.pop();
if (i % 10000000 == 0) {
System.out.println(i + " " + (Runtime.getRuntime().freeMemory() / 0124 / 1024));
}
}
System.out.println("done");
}
}
经测试,GC运行一直正常,也没有出现out of memory。
这么多数据,如果全部载入内存,需要94G内存。
运行结果:
0 724
10000000 1257
20000000 677
30000000 766
40000000 769
50000000 514
60000000 744
70000000 699
80000000 1028
90000000 1408
100000000 534
110000000 856
120000000 1062
130000000 937
140000000 562
150000000 789
160000000 778
170000000 893
180000000 698
190000000 1699
200000000 1532
210000000 4108
220000000 948
230000000 506
240000000 1147
250000000 557
260000000 3029
270000000 757
280000000 2284
290000000 1513
300000000 796
310000000 1127
320000000 1919
330000000 3064
340000000 1476
350000000 801
360000000 1573
370000000 2960
380000000 544
390000000 1015
400000000 1138
410000000 2960
420000000 1202
430000000 1115
440000000 2878
450000000 1724
460000000 1269
470000000 961
480000000 1420
490000000 4059
500000000 3190
510000000 629
520000000 831
530000000 715
540000000 2450
550000000 1156
560000000 623
570000000 863
580000000 1281
590000000 712
600000000 785
610000000 680
620000000 783
630000000 820
640000000 757
650000000 802
660000000 1228
670000000 610
680000000 1034
690000000 832
700000000 988
710000000 1119
720000000 1280
730000000 1189
740000000 662
750000000 576
760000000 1248
770000000 1081
780000000 702
790000000 1015
800000000 1055
810000000 1447
820000000 1015
830000000 629
840000000 879
850000000 980
860000000 2208
870000000 1846
880000000 823
890000000 779
900000000 587
910000000 1795
920000000 2820
930000000 1025
940000000 1806
950000000 550
960000000 584
970000000 626
980000000 597
990000000 607
done