标签:
RM源码中实现了一个有序并有优先级的Hook,ShutdownHookManager相比JVM本身的执行Hook方式具有如下两种特性(默认JVM执行,无序,并发)
1.顺序
2.有优先级
++++++++
类被初始化时候执行
1.设置shutdownInProgress标示
2.执行Hook按照调度优先级
private AtomicBoolean shutdownInProgress = new AtomicBoolean(false);
static {
Runtime.getRuntime().addShutdownHook( //添加了一个Hook,标示关闭正在执行。开始执行Hook,Hook执行顺序根据调度优先级
new Thread() {
@Override
public void run() {
MGR.shutdownInProgress.set(true);
for (Runnable hook: MGR.getShutdownHooksInOrder()) {
try {
hook.run(); //注意调用的run方法,不是start方法,hook为顺序执行
} catch (Throwable ex) {
LOG.warn("ShutdownHook ‘" + hook.getClass().getSimpleName() +
"‘ failed, " + ex.toString(), ex);
}
}
}
}
);
}
Set集合本身是没有顺序的,转换List,Collecitons.sort排序,并实现comparator,重新放到List
private Set<HookEntry> hooks =
Collections.synchronizedSet(new HashSet<HookEntry>());
/**
* Returns the list of shutdownHooks in order of execution,
* Highest priority first.
*
* @return the list of shutdownHooks in order of execution.
*/
List<Runnable> getShutdownHooksInOrder() {
List<HookEntry> list;
synchronized (MGR.hooks) {
list = new ArrayList<HookEntry>(MGR.hooks);
}
Collections.sort(list, new Comparator<HookEntry>() {//reversing comparison so highest priority hooks are first
@Override
public int compare(HookEntry o1, HookEntry o2) {
return o2.priority - o1.priority;
}
});
List<Runnable> ordered = new ArrayList<Runnable>();
for (HookEntry entry: list) {
ordered.add(entry.hook);
}
return ordered;
}
顺序,非并发执行Hook实现方式,主要逻辑。
总结:
执行单个Manager Hook,这个Manager Hook本身管理了,其他Hook,其他的Hook添加和删除都是通过这个MHook来执行的(Manager Hook)。
当系统退出的时候,MHook获取已根据调度优先级返回的Order Collection,顺序执行其中的run方法
赞.
---------------------
自己实际测试了一下,地址如下.
ShutdownHookManager顺序并有优先级的Hook
标签:
原文地址:http://www.cnblogs.com/yanbit/p/4739777.html