Reputation: 328
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
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
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
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
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
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