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

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

    VM is free to optimized the code to nullify s1 before method exit (as long as it's correct), so s1 might be eligible for garbage earlier.

    However that is hardly necessary. Many method invocations must have happened before the next GC; all the stack frames have been cleared anyway, no need to worry about a specific local variable in a specific method invocation.

    As far as Java the language is concerned, garbages can live forever without impact program semantics. That's why JLS hardly talks about garbage at all.

提交回复
热议问题