ChatGPT解决这个技术问题 Extra ChatGPT

Why would you ever implement finalize()?

I've been reading through a lot of the rookie Java questions on finalize() and find it kind of bewildering that no one has really made it plain that finalize() is an unreliable way to clean up resources. I saw someone comment that they use it to clean up Connections, which is really scary since the only way to come as close to a guarantee that a Connection is closed is to implement try (catch) finally.

I was not schooled in CS, but I have been programming in Java professionally for close to a decade now and I have never seen anyone implement finalize() in a production system ever. This still doesn't mean that it doesn't have its uses, or that people I've worked with have been doing it right.

So my question is, what use cases are there for implementing finalize() that cannot be handled more reliably via another process or syntax within the language?

Please provide specific scenarios or your experience, simply repeating a Java text book, or finalize's intended use is not enough, as is not the intent of this question.

HI finalize () method very well explained here howtodoinjava.com/2012/10/31/…
Most application and library code will never use finalize(). However, platform library code, such as SocketInputStream, which manages native resources on behalf of the caller, does so to try to minimize the risk of resource leaks (or uses equivalent mechanisms, such as PhantomReference, that were added later.) So the ecosystem needs them, even though 99.9999% of developers will never write one.
Update: finalize is now deprecated, as of Java 9. See the Question, Why is the finalize() method deprecated in Java 9?.

H
Hearen

You could use it as a backstop for an object holding an external resource (socket, file, etc). Implement a close() method and document that it needs to be called.

Implement finalize() to do the close() processing if you detect it hasn't been done. Maybe with something dumped to stderr to point out that you're cleaning up after a buggy caller.

It provides extra safety in an exceptional/buggy situation. Not every caller is going to do the correct try {} finally {} stuff every time. Unfortunate, but true in most environments.

I agree that it's rarely needed. And as commenters point out, it comes with GC overhead. Only use if you need that "belt and suspenders" safety in a long-running app.

I see that as of Java 9, Object.finalize() is deprecated! They point us to java.lang.ref.Cleaner and java.lang.ref.PhantomReference as alternatives.


Just make sure that an exception is never thrown by finalize(), or the garbage collector will not continue cleanup of that object, and you'll get a memory leak.
Finalize isn't guaranteed to be called, so don't count on it releasing a resource.
skaffman - I don't believe that (aside from some buggy JVM implementation). From the Object.finalize() javadoc: If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.
Your proposal can hide peoples bugs (not calling close) for a long time. I wouldn't recommend to do so.
I have actually used finalize for this exact reason. I inherited the code and it was very buggy and had a tendency to leave database connections open. We modified the connections to contain data about when and where they were created and then implemented finalize to log this information if the connection wasn't closed properly. It turned out to be a great help to track down the non-closed connections.
H
Hearen

finalize() is a hint to the JVM that it might be nice to execute your code at an unspecified time. This is good when you want code to mysteriously fail to run.

Doing anything significant in finalizers (basically anything except logging) is also good in three situations:

you want to gamble that other finalized objects will still be in a state that the rest of your program considers valid.

you want to add lots of checking code to all the methods of all your classes that have a finalizer, to make sure they behave correctly after finalization.

you want to accidentally resurrect finalized objects, and spend a lot of time trying to figure out why they don't work, and/or why they don't get finalized when they are eventually released.

If you think you need finalize(), sometimes what you really want is a phantom reference (which in the example given could hold a hard reference to a connection used by its referand, and close it after the phantom reference has been queued). This also has the property that it may mysteriously never run, but at least it can't call methods on or resurrect finalized objects. So it's just right for situations where you don't absolutely need to close that connection cleanly, but you'd quite like to, and the clients of your class can't or won't call close themselves (which is actually fair enough - what's the point of having a garbage collector at all if you design interfaces that require a specific action be taken prior to collection? That just puts us back in the days of malloc/free.)

Other times you need the resource you think you're managing to be more robust. For example, why do you need to close that connection? It must ultimately be based on some kind of I/O provided by the system (socket, file, whatever), so why can't you rely on the system to close it for you when the lowest level of resource is gced? If the server at the other end absolutely requires you to close the connection cleanly rather than just dropping the socket, then what's going to happen when someone trips over the power cable of the machine your code is running on, or the intervening network goes out?

Disclaimer: I've worked on a JVM implementation in the past. I hate finalizers.


Upvoting for extreme sarcasm justice.
This doesn't answer the question; it just says all the drawbacks of finalize() without giving any reasons someone would really want to use it.
@supercat: phantom references (for that matter all references) were introduced in Java 2
@supercat: sorry yes, by "references" I meant java.lang.ref.Reference and its subclasses. Java 1 did have variables :-) And yes, it had finalizers too.
@SteveJessop: If a base-class constructor asks other entities to alter their state on behalf of the object under construction (a very common pattern), but a derived-class field initializer throws an exception, the partially-constructed object should immediately clean up after itself (i.e. notify those outside entities their services are no longer required), but neither Java nor .NET offers any even-remotely-clean pattern via which that can happen. Indeed, they seem to go out of their way to make it hard for a reference to the thing needing cleanup to reach the cleanup code.
H
Hearen

A simple rule: never use finalizers.

The fact alone that an object has a finalizer (regardless what code it executes) is enough to cause considerable overhead for garbage collection.

From an article by Brian Goetz:

Objects with finalizers (those that have a non-trivial finalize() method) have significant overhead compared to objects without finalizers, and should be used sparingly. Finalizeable objects are both slower to allocate and slower to collect. At allocation time, the JVM must register any finalizeable objects with the garbage collector, and (at least in the HotSpot JVM implementation) finalizeable objects must follow a slower allocation path than most other objects. Similarly, finalizeable objects are slower to collect, too. It takes at least two garbage collection cycles (in the best case) before a finalizeable object can be reclaimed, and the garbage collector has to do extra work to invoke the finalizer. The result is more time spent allocating and collecting objects and more pressure on the garbage collector, because the memory used by unreachable finalizeable objects is retained longer. Combine that with the fact that finalizers are not guaranteed to run in any predictable timeframe, or even at all, and you can see that there are relatively few situations for which finalization is the right tool to use.


s
skaffman

The only time I've used finalize in production code was to implement a check that a given object's resources had been cleaned up, and if not, then log a very vocal message. It didn't actually try and do it itself, it just shouted a lot if it wasn't done properly. Turned out to be quite useful.


That's the only valid use. You can use almson-refcount for this purpose, since implementing it correctly and efficiently is tricky.
H
Hearen

I've been doing Java professionally since 1998, and I've never implemented finalize(). Not once.


How do I destroy the public class object then? It's causing issue in ADF. Basically it's suppose to reload the page (getting fresh data from an API), but it's taking the old object and showing the results
@InfantPro'Aravind' calling finalize doesn't remove the object. It's a method you implement that the JVM can choose to call if and when it garbage collects your object.
@PaulTomblin, ohk thanks for that detail. Any suggestion of refreshing a page on ADF?
@InfantPro'Aravind' No idea, never used ADF.
B
Bill K

The accepted answer is good, I just wanted to add that there is now a way to have the functionality of finalize without actually using it at all.

Look at the "Reference" classes. Weak reference, Phantom Reference & Soft Reference.

You can use them to keep a reference to all your objects, but this reference ALONE will not stop GC. The neat thing about this is you can have it call a method when it will be deleted, and this method can be guaranteed to be called.

As for finalize: I used finalize once to understand what objects were being freed. You can play some neat games with statics, reference counting and such--but it was only for analysis, but watch out for code like this (not just in finalize, but that's where you are most likely to see it):

public void finalize() {
  ref1 = null;
  ref2 = null;
  othercrap = null;
}

It is a sign that somebody didn't know what they were doing. "Cleaning up" like this is virtually never needed. When the class is GC'd, this is done automatically.

If you find code like that in a finalize it's guaranteed that the person who wrote it was confused.

If it's elsewhere, it could be that the code is a valid patch to a bad model (a class stays around for a long time and for some reason things it referenced had to be manually freed before the object is GC'd). Generally it's because someone forgot to remove a listener or something and can't figure out why their object isn't being GC'd so they just delete things it refers to and shrug their shoulders and walk away.

It should never be used to clean things up "Quicker".


Phantom references are a better way to keep track of which objects are being freed, I think.
upvoting for providing the best explanation of "weak reference" I've ever heard.
I'm sorry that this took me so many years to read this, but it really is a nice addition to the answers.
This pattern is now implemented as Cleaner in the JDK. It's more efficient, but not really different from finalization.
H
Hearen

I'm not sure what you can make of this, but...

itsadok@laptop ~/jdk1.6.0_02/src/
$ find . -name "*.java" | xargs grep "void finalize()" | wc -l
41

So I guess the Sun found some cases where (they think) it should be used.


I guess it is also a question of "Will Sun developer always be right"?
But how many of those uses are just implementing or testing support for finalize rather than actually using it?
I use Windows. How would you do the same thing in Windows?
@damryfbfnetsi: Try installing ack (beyondgrep.com) by way of chocolatey.org/packages/ack. Or use a simple Find in Files feature in $FAVORITE_IDE.
I tried this command in JDK 17 and result is ZERO :)
H
Hearen
class MyObject {
    Test main;

    public MyObject(Test t) {    
        main = t; 
    }

    protected void finalize() {
        main.ref = this; // let instance become reachable again
        System.out.println("This is finalize"); //test finalize run only once
    }
}

class Test {
    MyObject ref;

    public static void main(String[] args) {
        Test test = new Test();
        test.ref = new MyObject(test);
        test.ref = null; //MyObject become unreachable,finalize will be invoked
        System.gc(); 
        if (test.ref != null) System.out.println("MyObject still alive!");  
    }
}

====================================

result:

This is finalize

MyObject still alive!

=====================================

So you may make an unreachable instance reachable in finalize method.


For some reason, this code makes me think of zombie movies. You GC your object and then it stands up again...
above is good codes. I was wondering how to make the object re-reachable again just now.
no, above is bad codes. it's an example of why finalize is bad.
Remember that invoking System.gc(); is not a guarantee that the garbage collector will actually run. It is the GC's full discretion to cleanup heap (maybe still enough free heap around, maybe not fragmented to much, ...). So it is only a humble request by the programmer "please, could you hear me out and run?" and not a command "do run now as I say!". Sorry for using lingual words but it says it exactly how the JVM's GC works.
H
Hearen

finalize() can be useful to catch resource leaks. If the resource should be closed but is not write the fact that it wasn't closed to a log file and close it. That way you remove the resource leak and give yourself a way to know that it has happened so you can fix it.

I have been programming in Java since 1.0 alpha 3 (1995) and I have yet to override finalize for anything...


B
Bill the Lizard

You shouldn't depend on finalize() to clean up your resources for you. finalize() won't run until the class is garbage collected, if then. It's much better to explicitly free resources when you're done using them.


M
Michael Easter

To highlight a point in the above answers: finalizers will be executed on the lone GC thread. I have heard of a major Sun demo where the developers added a small sleep to some finalizers and intentionally brought an otherwise fancy 3D demo to its knees.

Best to avoid, with possible exception of test-env diagnostics.

Eckel's Thinking in Java has a good section on this.


H
Hearen

Be careful about what you do in a finalize(). Especially if you are using it for things like calling close() to ensure that resources are cleaned up. We ran into several situations where we had JNI libraries linked in to the running java code, and in any circumstances where we used finalize() to invoke JNI methods, we would get very bad java heap corruption. The corruption was not caused by the underlying JNI code itself, all of the memory traces were fine in the native libraries. It was just the fact that we were calling JNI methods from the finalize() at all.

This was with a JDK 1.5 which is still in widespread use.

We wouldn't find out that something went wrong until much later, but in the end the culprit was always the finalize() method making use of JNI calls.


How did you end up freeing up the memory allocated in JNI?
H
Hearen

Hmmm, I once used it to clean up objects that weren't being returned to an existing pool.

They were passed around a lot, so it was impossible to tell when they could safely be returned to the pool. The problem was that it introduced a huge penalty during garbage collection that was far greater than any savings from pooling the objects. It was in production for about a month before I ripped out the whole pool, made everything dynamic and was done with it.


J
John Meagher

When writing code that will be used by other developers that requires some sort of "cleanup" method to be called to free up resources. Sometimes those other developers forget to call your cleanup (or close, or destroy, or whatever) method. To avoid possible resource leaks you can check in the finalize method to ensure that the method was called and if it wasn't you can call it yourself.

Many database drivers do this in their Statement and Connection implementations to provide a little safety against developers who forget to call close on them.


u
user265243

Edit: Okay, it really doesn't work. I implemented it and thought if it fails sometimes that's ok for me but it did not even call the finalize method a single time.

I am not a professional programmer but in my program I have a case that I think to be an example of a good case of using finalize(), that is a cache that writes its content to disk before it is destroyed. Because it is not necessary that it is executed every time on destruction, it does only speed up my program, I hope that it i didn't do it wrong.

@Override
public void finalize()
{
    try {saveCache();} catch (Exception e)  {e.printStackTrace();}
}

public void saveCache() throws FileNotFoundException, IOException
{
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("temp/cache.tmp"));
    out.writeObject(cache);
}

I think a cache (of the type you would flush to disk) is a good example. And even if finalize is not called, no sweat.
A
Alexander Malfait

It can be handy to remove things that have been added to a global/static place (out of need), and need to be removed when the object is removed. For instance:

private void addGlobalClickListener() {
        weakAwtEventListener = new WeakAWTEventListener(this);

        Toolkit.getDefaultToolkit().addAWTEventListener(weakAwtEventListener, AWTEvent.MOUSE_EVENT_MASK);
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();

        if(weakAwtEventListener != null) {
            Toolkit.getDefaultToolkit().removeAWTEventListener(weakAwtEventListener);
        }
    }

This needs additional efforts, as when the listener has a strong reference to the this instance passed to it in the constructor, that instance will never become unreachable, hence the finalize() will never clean up anyway. If, on the other hand, the listener hold a weak reference to that object, as the name suggests, this construct risks getting cleaned up at times when it shouldn’t. Object life cycles are not the right tool for implementing application semantics.
H
Hearen

The accepted answer lists that closing a resource during finalize can be done.

However this answer shows that at least in java8 with the JIT compiler, you run into unexpected issues where sometimes the finalizer is called even before you finish reading from a stream maintained by your object.

So even in that situation calling finalize would not be recommended.


It would work, if the operation is made thread safe, which is a must, as finalizers may be called by arbitrary threads. Since correctly implemented thread safety implies that not only the close operation, but also the operations using the resource must synchronize on the same object or lock, there will be a happens-before relationship between the use and the close operation, which also prevents too early finalization. But, of course, at a high price for the entire usage…
J
JGFMK

iirc - you can use finalize method as a means of implementing a pooling mechanism for expensive resources - so they don't get GC's too.


H
Hearen

As a side note:

An object that overrides finalize() is treated specially by the garbage collector. Usually, an object is immediately destroyed during the collection cycle after the object is no longer in scope. However, finalizable objects are instead moved to a queue, where separate finalization threads will drain the queue and run the finalize() method on each object. Once the finalize() method terminates, the object will at last be ready for garbage collection in the next cycle.

Source: finalize() deprecated on java-9


H
Hearen

The resources (File, Socket, Stream etc.) need to be closed once we are done with them. They generally have close() method which we generally call in finally section of try-catch statements. Sometimes finalize() can also be used by few developers but IMO that is not a suitable way as there is no guarantee that finalize will be called always.

In Java 7 we have got try-with-resources statement which can be used like:

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
  // Processing and other logic here.
} catch (Exception e) {
  // log exception
} finally {
  // Just in case we need to do some stuff here.
}

In the above example try-with-resource will automatically close the resource BufferedReader by invoking close() method. If we want we can also implement Closeable in our own classes and use it in similar way. IMO it seems more neat and simple to understand.


H
Hearen

Personally, I almost never used finalize() except in one rare circumstance: I made a custom generic-type collection, and I wrote a custom finalize() method that does the following:

public void finalize() throws Throwable {
    super.finalize();
    if (destructiveFinalize) {
        T item;
        for (int i = 0, l = length(); i < l; i++) {
            item = get(i);
            if (item == null) {
                continue;
            }
            if (item instanceof Window) {
                ((Window) get(i)).dispose();
            }
            if (item instanceof CompleteObject) {
                ((CompleteObject) get(i)).finalize();
            }
            set(i, null);
        }
    }
}

(CompleteObject is an interface I made that lets you specify that you've implemented rarely-implemented Object methods like #finalize(), #hashCode(), and #clone())

So, using a sister #setDestructivelyFinalizes(boolean) method, the program using my collection can (help) guarantee that destroying a reference to this collection also destroys references to its contents and disposes any windows that might keep the JVM alive unintentionally. I considered also stopping any threads, but that opened a whole new can of worms.


Calling finalize() on your CompleteObject instances like you do in the above code implies that it might get called twice, as the JVM still might invoke finalize() once these objects actually became unreachable, which, due to the logic of finalization, might be before the finalize() method of your special collection gets called or even concurrently at the same time. Since I don’t see any measures to ensure thread safety in your method, you seem to be unaware of this…