Life cycle of local Java objects created during a method call

前端 未结 3 1722
一整个雨季
一整个雨季 2020-12-18 02:19

In a method call, if I create an object during that call. When are those objects garbage collected?

Are they placed on the heap and then garbage collected along w

3条回答
  •  清酒与你
    2020-12-18 02:58

    This is not so easy - in the very end every object is created in some method.

    The VM / compiler needs to make escape path analysis to detect if a reference of this object in some way can escape - imagine calling newObject.toString(). You and me know (hope) that this will do no harm and the object is still not referenced, as it will not link itself to a global variable. But the VM dows not.

    While a modern VM will do such analysis and treat real short lived objects special in garbage collection, from a "high level" point of view they are just objects. Everything else is sophisticated low level optimization.

    And anyway, as duffymo says - when exactly this objects are freed is uncertain.

提交回复
热议问题