过时的引用和内存不足错误

时间:2018-02-28 12:13:38

标签: java memory-management memory-leaks out-of-memory

为什么version4方法会抛出内存错误,但version3方法不会抛出它,我认为在这两种情况下都存在问题是“过时的引用”?

private static void version4() {
    int count = 0;
    long start = System.nanoTime();
    try {
        List<Calendar> list = new ArrayList<>();
        System.out.println(list.size());
        while(true){
            for (int i = 0; i < 1000; i++) {
                Calendar calendar = Calendar.getInstance();
                list.add(i, calendar);
            }
        }
    } catch (Error e) {
        e.printStackTrace();
    }
    long end = System.nanoTime();
    System.out.println("count: " + count + " | time:" + (end - start)/1000000);
}

private static void version3() {
    int count = 0;
    long start = System.nanoTime();
    try {
        Calendar[] calendars = new Calendar[1000]; 
        while(true){
            for (int i = 0; i < calendars.length; i++) {
                Calendar calendar = Calendar.getInstance();
                calendars[i] = calendar;
            }
        }
    } catch (Error e) {
        e.printStackTrace();
    }
    long end = System.nanoTime();
    System.out.println("count: " + count + " | time:" + (end - start)/1000000);
}

1 个答案:

答案 0 :(得分:3)

在这两种情况下,由于外部while (true),你会永远循环 但是在数组的情况下,在内部循环中,您将覆盖数组的旧值(长度为1000)。所以内存消耗大致不变 在ArrayList情况下,您在内部循环中添加新的Calendar对象。因此内存使用量不断增长:1000(第一个循环)+ 1000(第二个循环)+ ...