1

I don't quite understand the results. It's a test for termination condition in garbage collection. Here is the code

class Tank{

    Tank(boolean isEmpty, String name) {
    this.isEmpty  = isEmpty;
    this.name = name;
    }

    @Override
    protected void finalize() throws Throwable{
        if(this.isEmpty) {
            System.out.println(this.name + " is finalized ... ");
            super.finalize();
        }else{
            System.out.println(this.name + " is not finalized ... ");
        }
    }

    private boolean isEmpty;
    public String name;

    public boolean isEmpty() {
        return isEmpty;
    }

    public void setEmpty(boolean isEmpty) {
        this.isEmpty = isEmpty;
    }
}

public class GcTest {
    public static void main(String[] args) {
        new Tank(false, "t1");
        new Tank(true, "t2");
        System.gc();
    }
}

I ran the code several times.

1 - some of them output

t2 is finalized ... 
t1 is not finalized ... 

2 - Some of them output nothing.

3 - Some of them only output "t2 is finalized ... " or "t1 is not finalized ... "

What I don't understand is that case 2 and 3 happened. I thought as System.gc() is called at the end of the program, it is supposed to run every time and output t1 and t2 finalization information.

user1888955
  • 626
  • 1
  • 9
  • 27
  • There's no relation between being finalized and `isEmpty`, so your output makes no sense. +++ AFAIK, finalizers get run by a daemon thread, so it's not exactly part of the GC. The JVM may terminate before the daemon thread finishes. +++ Never use `finalize`. +++ In case you do, never ever rely on it. – maaartinus Dec 04 '16 at 16:57

0 Answers0