1
public class TestFinalize {


static int i = 0;

public TestFinalize() {
    i++;
}

protected void finalize(){
    i--;
}

public static void main(String[] args) {

    TestFinalize testFinalize = new TestFinalize();
    testFinalize = new TestFinalize();
    System.gc();
    System.out.println(i);

}
}

I expected that value of i will always be 1 in this case but when I ran this code multiple times it sometimes prints 1 and sometimes prints 2. Why is this happening?

M. Gorczyca
  • 39
  • 1
  • 2
  • But also VM triggered `finalize` calls run in their own thread. – Sotirios Delimanolis Jul 26 '17 at 00:39
  • 1
    You don’t have any thread synchronization between your `finalize()` method and the main thread printing the value of `i`, so even if the `finalize()` method got executed, which is not guaranteed, there is no guaranty that the main thread notices the new value. In principle, it’s even possible that the finalization of the first object runs concurrently to the construction of the second, having a data race between `i++` and `i--`, so even printing `0` is possible. Since it is legal to collect the second object as well, as it is not used, even printing `-1` could happen… – Holger Jul 26 '17 at 11:25

0 Answers0