When will the object be eligible for GarbageCollector?

2

From the code snippets below, in which the object created in new Pessoa("João") will be available to the garbage collector in the line: //outras instruções ?

They are all independent codes. They are not in the same class or file.

1

public void algumMetodo() {
    AlgumaClasse algumaClasse = new AlgumaClasse();
    Pessoa p = new Pessoa("João");
    algumaClasse.printaNome(p);
    //outras instruções
}

2

public void algumMetodo() {
    AlgumaClasse algumaClasse = new AlgumaClasse();
    algumaClasse.printaNome(new Pessoa("João"));
    //outras instruções
}

3

public void algumMetodo() {
    Pessoa p = new Pessoa("João");
    new AlgumaClasse().printaNome(p);
    //outras instruções
}

4

public void algumMetodo() {
    new AlgumaClasse().printaNome(new Pessoa("João"));
    //outras instruções
}

5

public void algumMetodo() {
    AlgumaClasse.printaNomeStatic(new Pessoa("João"));
    //outras instruções
}

Methods printaNome and printaNomeStatic :

public void printaNome(Pessoa p) {
    System.out.println(p.getNome());
}

public static void printaNomeStatic(Pessoa p) {
    System.out.println(p.getNome());
}
    
asked by anonymous 22.03.2017 / 13:13

1 answer

3

In 2, 4 and 5, in others the object remains referenced and can not be collected there. Possibly it will be collected at the end of this method (if it does not escape it in some way (put in another object that is not local to the method, another thread ), or return, which does not occur there because it is void ).

In 2, 4 and 5 the object is created, passed to another method (the ones that print) that keeps a reference to it, and at its end there is no more reference since in algumMetodo() does not have its own reference for this object, it can already be collected there.

Collection is always possible when there are no more references. Collection can occur any time you try to make an allocation and determine that there is no space in the memory arena.

    
22.03.2017 / 13:47