<p>There is a console Java application which is supposed to run until it is stopped by <kbd>Ctrl</kbd>+<kbd>C</kbd> or closing the console window. How that application can be programmed to execute a clean up code before exit?</p>

You could use a
Shutdown Hook
.
Basically you need to create a Thread which will perform your shutdown actions, and then
add it as a shutdown hook
. For example:
```
```
class ShutdownHook extends Thread
{
    public void run()
    {
        // perform shutdown actions
    }
}

// Then, somewhere in your code

Runtime.getRuntime().addShutdownHook(new ShutdownHook())
```
```