How to ensure finalize() is always called (Thinking in Java exercise)

前端 未结 5 853
情深已故
情深已故 2020-12-10 03:51

I\'m slowly working through Bruce Eckel\'s Thinking in Java 4th edition, and the following problem has me stumped:

Create a class with a fina

5条回答
  •  猫巷女王i
    2020-12-10 04:06

    Here's what worked for me (partially, but it does illustrate the idea):

    class OLoad {
    
        public void finalize() {
            System.out.println("I'm melting!");
        }
    }
    
    public class TempClass {
    
        public static void main(String[] args) {
            new OLoad();
            System.gc();
        }
    }
    

    The line new OLoad(); does the trick, as it creates an object with no reference attached. This helps System.gc() run the finalize() method as it detects an object with no reference. Saying something like OLoad o1 = new OLoad(); will not work as it will create a reference that lives until the end of main(). Unfortunately, this works most of the time. As others pointed out, there's no way to ensure finalize() will be always called, except to call it yourself.

提交回复
热议问题