Clean up code in finalize() or finally()?

前端 未结 9 1050
不知归路
不知归路 2020-12-19 04:16

I had the general view that clean up of resources is done in the finally block,
recently I found this particular code snippet in a class and it was overridi

9条回答
  •  借酒劲吻你
    2020-12-19 04:37

    There are a number of problems with the code in the question, including:

    • The big problem: It looks like you are trying to close a socket. Even if you don't close it properly, it will close in its own finaliser. Adding another finaliser doesn't make it any more closed.
    • An exception thrown by the first close will prevent the others from executing (as it happens, this doesn't matter in this example because of the peculiar behaviour of Socket).
    • If you do override finalize, leave it throwing Throwable (and add @Override). Technically you should also call the super in a finally block.
    • The Java Memory Model is mighty strange when it comes to finalisers (previous execution of code does not necessarily happen-before the execution of the finaliser). I would explain the problem, but what you need to know is that you need to stay away from finalisers.

    So: Always use finally for these things. finalize is extremely specialised (and PhantomReference are probably better is superficially more complicated).

提交回复
热议问题