Finalizers is Unpredictable,often Dangerous,and generally unnecessary.
Their use can cause erratic Behavior,poor performance,and portability problems.
Finalizers has a few valid Uses,which we ' ll cover later in this item,but as a rule of thumb,you should avoid finalizers.
C + + Programmers is cautioned not to think of finalizers as Java ' s analog of C + + destructors. In C++,destructors is the normal the Reclaim the resources associated with a object,a necessary counterpart to Constr Uctors. In java,the garbage collector reclaims the storage associated with a object when it becomes unreachable,requiring no spec Ial effort on the part of the programmer. C + + destructors is also used to reclaim other nonmemory resources. In java,the try-finally block are generally used for this purpose.
// try-finally block guarantees execution of termination method Foo foo=new foo (); try{ //do-what-must be-donewit foo}finally{//provide an Explicit termination method. // Explicit termination Method}
Explicit termination methods is typically used in combination with the try-finally construct to ensure termination.
But the finalizer should logs a warning if it finds that the resource have not been terminated.
// Finalizer Guardian Idiom class foo{ // Final object finalizerguardian=new object () { Protected Ovid Finalize Thros throwable{ ... // Finalize Outer Foo Object }}; // remainder omitted}
Effective Java English Second Edition reading notes Item 7:avoid finalizers