Is there a destructor for Java?

前端 未结 22 1380
[愿得一人]
[愿得一人] 2020-11-22 11:47

Is there a destructor for Java? I don\'t seem to be able to find any documentation on this. If there isn\'t, how can I achieve the same effect?

To make my question m

22条回答
  •  北海茫月
    2020-11-22 12:24

    I fully agree to other answers, saying not to rely on the execution of finalize.

    In addition to try-catch-finally blocks, you may use Runtime#addShutdownHook (introduced in Java 1.3) to perform final cleanups in your program.

    That isn't the same as destructors are, but one may implement a shutdown hook having listener objects registered on which cleanup methods (close persistent database connections, remove file locks, and so on) can be invoked - things that would normally be done in destructors. Again - this is not a replacement for destructors but in some cases, you can approach the wanted functionality with this.

    The advantage of this is having deconstruction behavior loosely coupled from the rest of your program.

提交回复
热议问题