简体   繁体   中英

Why is the finalize() method in java.lang.Object “protected”?

Out of curiosity,

Why is the finalize() method's access modifier is made as protected . Why cant it be public ? Can someone explain me any specific reason behind this?

Also, I came to know that finalize() method is called only once. If I call it twice in my program internally, what is happening? Will the garbage collector call this again?

private void dummyCall() {
    try {
        finalize();
        finalize();
    } catch (Throwable e) {
        e.printStackTrace();//NOT REACHES EXCEPTION
    }
}

I answer your question with another question:

Why finalize method shouldn't be protected?

In general, you should try to keep things as much private as possible. That's what encapsulation is all about. Otherwise, you could make everything public . finalize can't be private (since derived classes should be able to access it to be able to override it), so it should at least be protected but why give out more access when it's not desirable?


After reading your comment more carefully, I guess I see your main point now. I think your point is since everything derives from java.lang.Object and consequently accesses its protected members, it wouldn't make any difference for it (or any method in java.lang.Object for that matter) to be public as opposed to protected . Personally, I'd count this as a design flaw in Java. This is indeed fixed in C#. The problem is not why finalize is protected. That's OK. The real issue is that you shouldn't be able to call protected methods in the base class through an object reference of the base class type. Eric Lippert has a blog entry discussing why allowing such kind of access to protected members is a bad idea which is further elaborated on Stack Overflow in this question .

Why is the finalize() method's access modifier is made as protected. Why cant it be public?

It is not public because it shouldn't be invoked by anyone other than the JVM. However, it must be protected so that it can be overridden by subclasses who need to define behavior for it.

If i call it twice in my program, internally what is happening?

You can call it all you want, its just a method after all. However, much like public static void main(String [] args) , it has special meaning to the JVM

Will the garbage collector call this again?

Yes

  • finalize is meant to be called by the gc only and as such does not require public access
  • finalize is guaranteed to be called only once by the gc , calling it yourself will break this guarantee, as the gc wont know about it.
  • Any overriding class can make finalize public, which I believe is bad for the above reasons
  • finalize should not contain much code, as any exception thrown by finalize may kill the finalizer thread of the gc.

Rant against finalize()

  • Managing native resources or any resource which requires dispose() or close() to be called may cause hard to find bugs as they will only be released when the jvm runs out of memory, you should release resources manually. Finalize should only be used for debugging resource leaks or for cases where managing resources manually is too much work.
  • finalize will be called in an additional thread of the gc and may cause problems with resource locking and so on.
  • the reference classes like WeakReference and ReferenceQueue are an alternative (rather complex) way to deal with cleanup and may have the same problems as finalize() for native resources.

Beware of errors in the above statements, I'm a bit tired :-)

Check out this link which discusses it.

Basically, it would make the most sense for it to be private , as it should only be called by the JVM (garbage collector). But in order to allow a subclass to call the parent finalize() method as part of its finalize() , it has to be protected .

( Edit - And just a general caution - use of the finalize() method is generally discouraged as there's no way of ensuring that it will ever be called. Although that doesn't mean that you'll never have occasion to use it - it's just rare.)

The part about finalize() being called only once applies only to the calls from the GC. You can imagine the object as having a hidden flag " finalize() was called by the GC", and the GC checking that flag to know what to do with the object. The flag is not impacted in any way by your own handmade calls to finalize() .

On finalization, read this article from Hans Boehm (who is well-known for his work on garbage collection). This is an eye-opener about finalization; in particular, Boehm explains why finalization is necessarily asynchronous. A corollary is that while finalization is a powerful tool, it is very rarely the right tool for a given job.

It's not public (or default access) because it's meant to be called by the JVM internally when the object is garbage collected - it's not meant to be called by anything else. And it's not private because it's meant to be overridden and you can't override private methods.

If i call it twice in my program, internally what is happening? Will the garbage collector will call this again?

Probably yes, but it's hard to imagine a scenario where this would make any kind of sense - the point of finalize() is to do cleanup when an object is garbage collected. And it doesn't even do that well, so it's really something you should avoid altogether rather than experiment with.

我认为finalize被保护的原因是,它可能被JDK中的某些类所覆盖,而那些被覆盖的方法被JVM调用。

finalize() is only used by the JVM to clean up resources when the object is collected. It's reasonable for a class to define what actions should be taken on collection, for which it may need to access super.finalize(). It doesn't really make sense for an outside process to call finalize(), since an outside process doesn't have control over when the object is collected.

Also, I came to know that finalize() method is called only once. If i call it twice in my program, internally what is happening?

You probably ask this under impression of C++ ~destructors. In java finalize () method doesn't do any magic (like clearing memory). It's supposed to be called by garbage collector. But not vice versa.

I recommend you to read correspondent chapter in Joshua Bloch's "Effective Java". It says that using finalizers is a bad practice and can cause performance and other issues, and there are only several cases when they should be used. The chapter begins with next words:

Finalizers are unpredictable, often dangerous, and generally unnecessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM