Search code examples
javadesign-patternsshutdown

Design Pattern to correctly exit a running program from multiple locations


I have a system written in java where I have multiple distinct objects each with different resources in use. Some have connections to activeMQ queues, some have network connections and others have open files. Some also contain running threads.

When a fatal error occurs anywhere in this system, I need to shut it down and correctly close all resources and stop all running threads.

My problem arises when the object that caused the error needs to start the shutdown process. This object does not know about the other objects that have open files and so on. So it can basically release all its resources and that is it.

I am looking for a clean way to achieve this without getting messy and passing multiple object references around the system.

Any insight is appreciated. Thank you.


Solution

  • Create a central Lifecycle object which all of these other objects in your application have a reference to, and which in turn has a reference to all of 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 in turn call object.onShutdown() on all of the objects registered with it, in order to give these objects a chance to close their 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 beans can extend a certain interface to be notified when the container is shutting down.