Is unused object available for garbage collection when it's still visible in stack?

前端 未结 5 1457
心在旅途
心在旅途 2020-12-30 01:44

In the following example there are two functionally equivalent methods:

public class Question {

    public static String method1() {
        String s = new          


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-30 02:09

    No, because your code could conceivably retrieve it and do something with it, and the abstract JVM does not consider what code is coming ahead. However, a very, very, very clever optimizing JVM might analyze the code ahead and find that there is no way s1 could ever be referenced, and garbage collect it. You definitely can't count on this, though.

提交回复
热议问题