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

前端 未结 5 1466
心在旅途
心在旅途 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:21

    in first of them string "s1" is clearly available for garbage collection before return statement

    It isn't clear at all. I think you are confusing 'unused' with 'unreachable'. They aren't necessarily the same thing.

    Formally speaking the variable is live until its enclosing scope terminates, so it isn't available for garbage collection until then.

    However "a Java compiler or code generator may choose to set a variable or parameter that will no longer be used to null to cause the storage for such an object to be potentially reclaimable sooner" JLS #12.6.1.

提交回复
热议问题