首页 > 解决方案 > 如果在无限循环中声明了任何变量/对象,那么关于内存的情况会怎样?

问题描述

我想知道以下场景在内存方面的表现。

此外

  1. 每次迭代后前一个对象会发生什么。

  2. 垃圾收集会出现吗?如果是,那么在什么时候?

假设有一个人类。

public class Person {
    String name;    
    public Person() {
    this.name = "foo";
    }
}

我们在 main 方法中有一个无限循环

   while(true){
        Person p = new Person();
        System.out.println(p);
    }

标签: javamemorymemory-managementgarbage-collectionheap-memory

解决方案


  1. What will happen to the previous object after each iteration.

It will be eligible for GC, as it is no longer in scope.

  1. Does Garbage Collection comes into picture? If yes, then at which point ?

As this is a short-lived object, very soon. There might even be optimizations in place (such as stack allocation) that don't require the GC to do any work.


推荐阅读