tags:

views:

4200

answers:

16

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 provided specific scenarios or your experience, simply repeating a Java text book, or finalize's intended use is not enough, and is not the intent of this question.

+7  A: 

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

Paul Tomblin
+1  A: 

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.

John Meagher
+4  A: 

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.

Bill the Lizard
+34  A: 

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.

John M
I guess I generally document well and then yell at people when they don't read the documentation. I guess this would help too. *grin*
Spencer K
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.
skaffman
Finalize isn't guaranteed to be called, so don't count on it releasing a resource.
flicken
Remember that finalize also impose performance penalty due to the fact that it takes more than one GC to clean the object!
Shimi Bandiel
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.
John M
Your proposal can hide peoples bugs (not calling close) for a long time. I wouldn't recommend to do so.
kohlerm
Why not just put an assertion within finilize checking that the object is ready for disposal, i.e. "closed" instead of writting to a log?
Totophil
If you need that "belt and suspenders" safety to keep an important system running, I don't want to have an AssertionError thrown. I'd like to maximize the chance that the system keeps running by doing the cleanup, while leaving info in a log so I can realize something's wrong.
John M
+1 for 30 even.
fastcodejava
Finalize hurts GC performance, since the garbage collector has to check twice if the object has been collected.
mdma
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.
brainimus
A: 

You shouldn't use it in production. I did once during my first year of J2EE, the code caused some kind of error in production.

In C++ deconstructors, (counter part to finalize()) are needed to clean up memory off the heap. With Java this isn't needed.

Zombies
C++ destructors are much more powerful than to just clean up memory, as they allow RAII programming, where any kind of resources (like locks, open file, etc.) are automatically released correctly when the object using them goes out of scope.
lothar
+7  A: 

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.

skaffman
+1  A: 

Be careful 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.

Steven M. Cherry
+21  A: 

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 which require that 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.

Steve Jessop
+1  A: 

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.

+5  A: 

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.

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, etc.

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.

Another thing to watch out for. Any time you see anything like this anywhere in code (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 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 GCd). Generally it's because someone forgot to remove a listener or something and can't figure out why their object isn't being GCd 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".

Bill K
Phantom references are a better way to keep track of which objects are being freed, I think.
Bill Michell
+8  A: 

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.

Tom
+1  A: 

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.

Michael Easter
+11  A: 

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.

itsadok
+3  A: 

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...

TofuBeer
+4  A: 
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.

Kiki
A: 

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);
}