Java – design pattern for correctly exiting a running program from multiple locations
I have a system written in Java. I have multiple different objects, and each object has different resources in use Some have connections to active MQ queues, some have network connections, and some have open files Some also contain running threads
When a fatal error occurs anywhere in this system, I need to shut it down and properly close all resources and stop all running threads
My problem arises when the object causing the error needs to start the shutdown process This object is unaware of other objects with open files, etc So it can basically release all resources, that's it
I'm looking for a clean way to do this without messing up and passing multiple object references around the system
Any opinion is appreciated thank you.
Solution
Create a central lifecycle object that can be referenced by all other objects in the application, and the object references all these other objects In addition, each of these objects should implement a common interface, such as
public interface ShutdownListener { void onShutdown(); }
When one of the objects needs to start an orderly shutdown, it can call lifecycle Shutdown (), which can call object in turn Onshutdown() registers all objects on them to provide them with an opportunity to close them resources.
This is basically the observer pattern
If you use a dependency injection container, such as spring, this type of thing is built-in - your bean can extend an interface to be notified when the container closes