0

I thought Object finalize() is always called before the object is retired. In this test, I observed that when object is added to a collection and collection is cleared, the finalize is not called on the object. It is definitely called on the list. Note, I turned escape analysis off -XX:-DoEscapeAnalysis to prevent optimization. Could somebody explain to me, please?

    List<MyClass> list=new ArrayList<>(); 
    MyClass c=new MyClass();
    listM.add(c);

    list.clear();
    list=null;
Vortex
  • 789
  • 12
  • 21
  • 1
    Please provide a full example. What behavior do you expect out of your object's finalization? Also, are you sure that the variable `c` has gone out of scope? Because at no point in the code that you posted does it go out of scope. – nasukkin Oct 03 '16 at 23:34
  • 4
    There's no guarantee `finalize` will *ever* run. Also, why do you think the list's `finalize` is getting called? – user2357112 Oct 03 '16 at 23:35
  • And as @user2357112 stated, it is poor practice to expect `finalize` to ever be called consistently. – nasukkin Oct 03 '16 at 23:35
  • There is no guarantee when finalize will be called other than when the Garbage Collector runs. This question sums it up well: http://stackoverflow.com/questions/2506488/when-is-the-finalize-method-called-in-java. I really don't do anything at all in Java finalize anymore as you have no control over when it happens – Bob Kuhar Oct 03 '16 at 23:40
  • 3
    You still have a reference to the object yourself via `c`. Your question therefore makes no sense. – user207421 Oct 04 '16 at 00:10
  • Oops, EJP - thank you, totally my miss. – Vortex Oct 04 '16 at 00:16

0 Answers0