Effective Java English Second Edition reading notes Item 7:avoid finalizers

Source: Internet
Author: User
Tags finally block

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.