开发者

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 t开发者_如何学Pythonhat 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.


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.


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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜