Yicanis
Yicanis

Reputation: 328

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?

Upvotes: 4

Views: 2246

Answers (5)

Affe
Affe

Reputation: 47974

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!

Upvotes: 6

Tim Bender
Tim Bender

Reputation: 20442

Technically, it isn't possible to give and answer because we haven't seen the implementation for Dog#bark().

Generally, the answer is YES, the Dog instance will be collected AFTER the method is run, it just isn't possible to know exactly when. The reason for this is that unless the bark method shares the reference to the Dog object with another object, the particular instance of Dog will no longer be reachable. The next time the Garbage Collector runs, it will determine that Dog is not reachable and collect the heap space that was used to keep it.

Upvotes: 1

fresskoma
fresskoma

Reputation: 25781

This blog post provides a good explanation on how the garbage collection process works. To summarize:

An Object becomes eligible for Garbage collection if its not reachable from any live threads or any static refrences. It (the Garbage Collector) will only trigger if JVM thinks it needs a garbage collection based on Java heap size.

Therefore you shouldn't make assumptions on when any object will be garbage collected.

Upvotes: 0

kosa
kosa

Reputation: 66637

It depend on reach ability of the object. If object is not reachable then it is eligilble for GC. When to GC is dependent on JVM implementation. Truth About Garbage Collection

Upvotes: 0

Hakan Serce
Hakan Serce

Reputation: 11256

Simply no. I mean, the timing does not have to be like that.

All Java Objects are allocated in the heap and collected by the GarbageCollector. And GarbageCollector runs in background, with almost no constraint on when to perform actual garbage collection.

Upvotes: 2

Related Questions