If you have threads that can be legally stopped at any time, at any time within their cycle, at any point in any method that they call, and I can warn you that this is very unlikely, you can stop all of them when you exit the program. This will throw an exception in each thread, and finally blocks will execute.
However, the correct way to achieve your goal and the graphical interface, separate from the program logic, is to release one "exit" from the graphical interface, which initiates the entire cleaning of the application, which is written in a completely different class. If you have threads, then implement interrupt mechanism in each of them.
There are many ways to achieve output signaling. For example, your business code may register a GUI receiver for a special event, which will clear it. You can also have a thread that does nothing but await on a CountDownLatch , which will be countDown from the GUI.
Please in no case use the disconnect hook . This is the dirtiest mechanism you can imagine, and it exists only as a last resort, when all regular cleaning procedures fail. It should never be used as part of a normal shutdown procedure.
Thus, there is no clear way to clean applications. You must implement specific mechanisms for each specific problem.
Marko topolnik
source share