0

Saw this question somewhere, and it makes me confused about the gc concept. So when it comes to line

s2 = null;

Which object is eligible for gc? I think s1 should be the eligible one. What do you think?

Following are the code. Please forgive me about any issue of the format as I'm using mobile.

class Student {
    String name;
    int age;
}

And

public class Test {
    public static void main(String [] args){
        Student s1 = new Student();
        Student s2 = new Student();
        Student s3 = new Student();

        s1 = s3;
        s3 = s2;
        s2 = null;
    }
}
Guy
  • 46,488
  • 10
  • 44
  • 88
  • When the `main()` method ends, all three variables will be garbage collected. Also, had you extended your code in `main()` further, some variables could also have become eligible for GC if they were no longer being used/referenced. – Tim Biegeleisen Jan 08 '17 at 07:20
  • The only line that makes an object lose all references to it is `s1 = s3;`. The rest of the objects become eligible for GC from just going out of scope. – 4castle Jan 08 '17 at 07:25
  • @4castle From the method exiting. There is no 'going out of scope' instruction in the bytecode. – user207421 Jan 08 '17 at 07:45
  • @EJP: the implications of local variables having no scope, is, that the JVM may consider them non-existent at any time, if not subsequently read. If the optimizer were active in this short program, all objects were eligible for gc *at any time*, if they were ever created. I think [this answer](http://stackoverflow.com/a/14171110/2711488) nails it… – Holger Jan 11 '17 at 12:34

0 Answers0