How do you write a deconstructor in Java?

后端 未结 7 2090
萌比男神i
萌比男神i 2020-12-20 08:17

I came across this question and am looking for some ideas?

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 08:53

    Automatic object "destruction" in Java never happens at a guaranteed time. The only grantees for garbage collection are that before an object is collected the finalizer method will be called. Of course the garbage collector is never guaranteed to run, or do anything when it does run. So there is no guarantee that the finalize method will be called.

    If you want to simulate C++ destructors in Java the best way is to use the following idiom (there are variations when it comest to exception handling - I'll just show the simplest case here):

    final Resource r;
    
    r = new Resource();
    
    try
    {
        r.use();
    }
    finally
    {
        r.cleanup();
    }
    

    where the "cleanup" method is the "destructor".

    This is more like the C++ Resource Acquisition Is Initialization idiom which is really for stack based objects, but isn't as nice.

提交回复
热议问题