-1

I'm writing a program, so I'm having problems.

Why the finalize() method is not called?

public class ExOne extends Thread {
    private String sD;
    ExOne(String startUp, String shutDown){
        System.out.println("Start-up message is: " + startUp);
        sD = shutDown;
    }
    public void finalize() {
        System.out.println("Shut-down message is: " + sD);
    }
    @Override
    public void run() {
        try {
            for (int i = 0; i < 3; i++) {
                System.out.println("Message " + String.valueOf(i));
                Thread.sleep(1000);
            }
        }
        catch (InterruptedException e){
            System.out.println(e);
        }
        System.gc();
        System.runFinalization();
    }
}

public class Main {
    public static void main(String[] args) {
        ExOne exOneobj = new ExOne("start", "stop");
        exOneobj.start();
    }
}

So input is:

Start-up message is: start
Message 0
Message 1
Message 2

Process finished with exit code 0

And no message "Shut-down message is stop". Please help me.

What is wrong?

Dina
  • 1
  • 2
    Nowhere in your program does `exOneobj` go out of scope, so it never gets garbage collected, so `finalize()` is never run. – azurefrog Apr 21 '17 at 21:30
  • `finalize()` is executed just before garbage collected the object (`exOneobj`) to release memory space but in you program when `run` exits `exOneobj` is still in memory but program ends so that `finalize()` is not called – Mohsin AR Apr 21 '17 at 21:41

1 Answers1

-1

finalize() is executed when object is cleared by garbage collector and in your case it never happens since program ends before exOneobj has chance to be cleared.

reynev
  • 326
  • 2
  • 5