When will the object be eligible for the Garbagecollector?

Asked

Viewed 166 times

2

From the code snippets below, in which the object created in new Pessoa("João") will be available for the Garbage Collector on 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());
}

1 answer

3


In options 2, 4 and 5. In the others the object is still referenced and cannot be collected there. Possibly it will be collected at the end of the method (if it does not escape it somehow (put in another object that is not local to the method, other 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 (those that print) that maintains a reference to it, and in its end there is no more reference since in the algumMetodo() does not have its own reference to this object, it can already be collected.

The collection is always possible when there are no more references. The start of the collection can occur at any time trying to make an allocation and determine that there is a lack of space in that memory arena.

  • 1

    Why not the 2 too?

  • 1

    @Igorventurelli is, I saw creating the object and storing in variable and I found that it was he who had been sent, I did not pay attention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.