Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if a finalizer makes an object reachable?

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?

like image 404
Bart van Heukelom Avatar asked Sep 27 '10 21:09

Bart van Heukelom


People also ask

How does a finalizer work?

You can use finalizers to control garbage collection of resources by alerting controllers to perform specific cleanup tasks before deleting the target resource. Finalizers don't usually specify the code to execute. Instead, they are typically lists of keys on a specific resource similar to annotations.

Why should you avoid the finalize () method in the object class?

“This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.” So, in one way we can not guarantee the execution and in another way we the system in danger.

Why is it preferred to not use finalize for clean up?

The preferred way is to implement IDisposable along with the dispose pattern. Finalizers are time-limited and the GC will terminate a finalizer if it blocks for too long - this is the primary reason to avoid it where possible. Dispose is just a method call and is not time-limited.

What is finalize () in Java?

Finalization is a feature of the Java programming language that allows you to perform postmortem cleanup on objects that the garbage collector has found to be unreachable. It is typically used to reclaim native resources associated with an object. Here's a simple finalization example: Copy. Copied to Clipboard.


1 Answers

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.

like image 59
Jon Skeet Avatar answered Sep 29 '22 18:09

Jon Skeet