Mike L.
Mike L.

Reputation: 589

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.

Upvotes: 3

Views: 708

Answers (3)

Moe Matar
Moe Matar

Reputation: 2054

A java virtual machine allows the registration of Shutdown Hooks. Your database connection pool, your file IO manager, your activeMQ queues manager can all independently register their own shutdown hooks that each close all their resources cleanly.

A shutdown hook is a Thread that requires a reference to the resource manager(s) it's responsible for shutting down. The run method of this thread will be executed when the application is terminated. Your application has access to register a shutdown hook anywhere as Runtime.getRuntime() is available as a static call, so no need to wire it into the areas of the application that need it (although it is advisable that you register such shutdown hooks at the time of the creation of each resource manager).

More information here.

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)

Upvotes: 1

Alex Gitelman
Alex Gitelman

Reputation: 24732

You may be able to use Shutdown hook for that. In it you can notify all related objects, which, of course, need to be registered somewhere.

Upvotes: 1

matt b
matt b

Reputation: 139971

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.

Upvotes: 5

Related Questions