What if a finalizer makes an object reachable?
Asked Answered
P

5

7

In Java, finalize is called on an object (that overrides it) when it's about to be garbage collectioned, so when it's unreachable. But what if the finalizer makes the object reachable again, what happens then?

Phillips answered 27/9, 2010 at 21:37 Comment(0)
A
9

The object will not be collected until it gets unreachable again.

According to the JavaDoc, finalize() will not be called again.

Arrearage answered 27/9, 2010 at 21:44 Comment(0)
N
10

Then the object doesn't get garbage collected, basically. This is called object resurrection. Perform a search for that term, and you should get a bunch of interesting articles. As Jim mentioned, one important point is that the finalizer will only be run once.

Nyctalopia answered 27/9, 2010 at 21:43 Comment(0)
A
9

The object will not be collected until it gets unreachable again.

According to the JavaDoc, finalize() will not be called again.

Arrearage answered 27/9, 2010 at 21:44 Comment(0)
H
7

If you read the API description carefully, you'll see that the finalizer can make the object reachable again. The object won't be discarded until it is unreachable (again), but finalize() won't be called more than once.

Hydantoin answered 27/9, 2010 at 21:43 Comment(1)
Actually, the finalizer does make the object strongly reachable via rooted reference between the time the object is found to be unreachable and the time its finalizer is run. If during that time the object that was found to be unreachable becomes the only surviving reference to some other object, that other object will not be collectable until the finalizer is run or that reference is invalidated via some other means.Indemnification
M
3

Yeah, this is why you don't use finalizers (Well, one of the many reasons).

There is a reference collection that is made to do this stuff. I'll look it up and post it here in a sec, but I think it's PhantomReference.

Yep, PhantomReference:

Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed. Phantom references are most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.

Macaroon answered 27/9, 2010 at 21:43 Comment(1)
No, it's a reason why not to write a very broken finaliser (if there weren't enough other reasons).Anagnos
J
3

It actually does another pass to check and make sure there are no more references to the object. Since it will fail that test on its second pass, you'll end up not freeing the memory for the object.

Because finalize is only called a single time for any given object, the next time through when it has no references, it will just free the memory without calling finalize. Some good information here on finalization.

Junkie answered 27/9, 2010 at 21:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.