Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do local variables get collected after method is done running

For example

public void doSomething() {
   Dog smallDog = new Dog();
   smallDog.bark();
}

will the dog object be collected after this method is run?

like image 382
Yicanis Avatar asked Jan 17 '23 01:01

Yicanis


1 Answers

It can become eligible to be collected when the method returns. When garbage collection actually happens is some unknown time in the future.

It is impossible to tell for sure without seeing the implementation of bark().

If this is your bark:

public void bark() {
   BarkListeners.callBack(this);
}

public class BarkListeners {
  private static final List<Dog> barkers = new ArrayList<Dog>();

  public static void callBack(Dog dog) {
    barkers.add(dog);
  }
}

Then no, it won't be getting garbage collected!

like image 99
Affe Avatar answered Jan 30 '23 05:01

Affe