Reputation: 1229
Hypothetically there is a code
actionService.processAction(new HelloWorldAction("Hello world", helloWorldRepository))
Where helloWorldRepository
is Spring bean.
Will garbage collector some-when clean that HelloWorldAction
object or because this object have reference to helloWorldRepository
it will live forever in JVM and its better to use WeakReference if I want to avoid this situation?
Thanks.
Upvotes: 0
Views: 1255
Reputation: 691635
A short-lived object has a reference to a long-lived object. That causes no problem: the short-lived object, when it's not reachable anymore, can be garbage collected. And it should quickly become unreachable if nothing has a reference to it.
There would be a problem if a long-lived object kept references to short-lived objects. Then the short-lived objects wouln't be GCed.
Upvotes: 3
Reputation: 31053
An object is not kept alive simply because it holds a reference to some other object (with a different lifetime). It's just the other way around: your HelloWorldAction
will keep the helloWorldRepository
object alive, i.e., all objects being referenced by HelloWorldAction
will live at least as long as the HelloWorldAction
instance, but if the last reference to the HelloWorldAction
instance goes out of scope, it becomes eligible for garbage collection, regardless of the references, it itself holds.
Upvotes: 1
Reputation: 12880
Instance of HelloWorldAction
is eligible for garbage collection when it is totally unreferenced. i.e. you don't have any reference to get it back. So, As a rule, when you want to make it eligible for garbage collection, remove all references to it. There shouldn't be any reference pointing to it
Upvotes: 1