How to ensure a piece of code is run before exiting a java application

后端 未结 4 2027
庸人自扰
庸人自扰 2021-01-13 00:42

I\'m using a licensed API which has a method to acquire/release a license object from a license server that has a finite number of licenses. At the beginning of my applicati

4条回答
  •  逝去的感伤
    2021-01-13 01:34

    For exceptions, you can wrap the body of main in a try/catch/block. For handling the SIGTERM signal, you can add a shutdown hook. However, the shutdown hook is not guaranteed to get triggered for a signal like SIGKILL.

    From Java doc:

    In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.

提交回复
热议问题