一、引言
在开发中我们如果要在关闭spring容器后释放一些资源,通常的做法有如下几种:
1.在方法上加上@PreDestroy注解
2.实现DisposableBean接口,实现其destroy方法
比较常用的是第一种实现,因为其足够简便。下面就来分析一下它的实现原理,看它是在哪一个环节被触发的。
二、开始分析
我们先移步到CommonAnnotationBeanPostProcessor
这个类中,看如下一段代码:
public CommonAnnotationBeanPostProcessor() {
setOrder(Ordered.LOWEST_PRECEDENCE - 3);
setInitAnnotationType(PostConstruct.class);
setDestroyAnnotationType(PreDestroy.class);
ignoreResourceType("javax.xml.ws.WebServiceContext");
}
可见在CommonAnnotationBeanPostProcessor的无参构造函数中设置了一个默认的DestroyAnnotationType,即PreDestroy
.在它的上方我们也看到了经常使用的PostConstruct
,其实原理是一致的,只是spring帮我们控制了调用的顺序而已。
而CommonAnnotationBeanPostProcessor是实现了BeanFactoryAware
和BeanFactoryAware
的,也就是spring在启动的时候会找到这些扩展接口的子类型进行实例化。从而实现一些个性化的功能,例如:注解、配置注入、初始化、关闭操作等等。由于本文的重点在PreDestroy
,所以不会过多的讲spring的加载过程。
接下来深入看看在哪里使用到了PreDestroy:
{
if (destroyAnnotationType != null) {
if (method.getAnnotation(destroyAnnotationType) != null) {
currDestroyMethods.add(new LifecycleElement(method));
if (debug) {
logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method);
}
}
}
}
});
initMethods.addAll(0, currInitMethods);
destroyMethods.addAll(currDestroyMethods);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
return new LifecycleMetadata(clazz, initMethods, destroyMethods);
}
看这一段代码,首先判断destroyAnnotationType它是否为空,显然这里不为空,这里指定了PreDestroy
,然后再判断这个注解上是否有@PreDestroy注解,如果有,就将该Method
包装成一个LifecycleElement
添加到一个List中,然后将其添加到了另外一个集合destroyMethods中。接下来看一下哪里在使用这个destroyMethods集合。
移步到InitDestroyAnnotationBeanPostProcessor
中,看到如下代码:
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
metadata.invokeDestroyMethods(bean, beanName);
}
catch (InvocationTargetException ex) {
String msg = "Invocation of destroy method failed on bean with name '" + beanName + "'";
if (logger.isDebugEnabled()) {
logger.warn(msg, ex.getTargetException());
}
else {
logger.warn(msg + ": " + ex.getTargetException());
}
}
catch (Throwable ex) {
logger.error("Failed to invoke destroy method on bean with name '" + beanName + "'", ex);
}
}
这个findLifecycleMetadata
方法通过调用buildLifecycleMetadata方法最终调用到了最上面的那段代码,该metadata也就持有了所有加了PreDestroy
注解的方法列表。接下来就是利用反射invoke
目标类即可实现。
public void invokeDestroyMethods(Object target, String beanName) throws Throwable {
Collection destroyMethodsToUse =
(this.checkedDestroyMethods != null ? this.checkedDestroyMethods : this.destroyMethods);
if (!destroyMethodsToUse.isEmpty()) {
boolean debug = logger.isDebugEnabled();
for (LifecycleElement element : destroyMethodsToUse) {
if (debug) {
logger.debug("Invoking destroy method on bean '" + beanName + "': " + element.getMethod());
}
element.invoke(target);
}
}
}
三、再深入一点
如果想要优雅的退出,@PreDestroy能否满足要求呢?因为我们常用的做法就是注册一个钩子程序,当我们kill进程时(非 kill -9).jvm会收到操作系统一个终端,来做一些资源收尾的操作。
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
logger.info("shutdown hook run.");
try {
} catch (Exception e) {
}
}
}));
如果spring想要优雅退出,必要要借助于hook,不然是没法影响中断的。接下来看一眼spring是怎么实现的。其实在AbstractApplicationContext
中有这样一个方法:
public void registerShutdownHook() {
if (this.shutdownHook == null) {
this.shutdownHook = new Thread() {
public void run() {
synchronized(AbstractApplicationContext.this.startupShutdownMonitor) {
AbstractApplicationContext.this.doClose();
}
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
}
springboot会通过启动main函数时调用refreshContext
来注册钩子程序:
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
所以要想实现优雅关闭资源,使用@PreDestroy注解即可。
四、钩子程序的实现原理
class ApplicationShutdownHooks {
/* The set of registered hooks */
private static IdentityHashMap hooks;
static {
try {
Shutdown.add(1 /* shutdown hook invocation order */,
false /* not registered if shutdown in progress */,
new Runnable() {
public void run() {
//被sequence方法调用
runHooks();
}
}
);
hooks = new IdentityHashMap<>();
} catch (IllegalStateException e) {
// application shutdown hooks cannot be added if
// shutdown is in progress.
hooks = null;
}
}
}
看一下runHooks()方法:
static void runHooks() {
Collection threads;
synchronized(ApplicationShutdownHooks.class) {
threads = hooks.keySet();
hooks = null;
}
for (Thread hook : threads) {
hook.start();
}
for (Thread hook : threads) {
while (true) {
try {
hook.join();
break;
} catch (InterruptedException ignored) {
}
}
}
}
}
其实就是把hooks里的线程全部拿到然后启动,并且等待执行结束。添加hook即把线程存放在IdentityHashMap中。当调用Shutdown.add()的时候其实是将该线程存放在Shutdown的成员变量数组中。
static void add(int slot, boolean registerShutdownInProgress, Runnable hook) {
synchronized (lock) {
if (hooks[slot] != null)
throw new InternalError("Shutdown hook at slot " + slot + " already registered");
if (!registerShutdownInProgress) {
if (state > RUNNING)
throw new IllegalStateException("Shutdown in progress");
} else {
if (state > HOOKS || (state == HOOKS && slot <= currentRunningHook))
throw new IllegalStateException("Shutdown in progress");
}
hooks[slot] = hook;
}
}
接下来看一下Shutdown的sequence
方法:
private static void sequence() {
synchronized (lock) {
/* Guard against the possibility of a daemon thread invoking exit
* after DestroyJavaVM initiates the shutdown sequence
*/
if (state != HOOKS) return;
}
runHooks();
boolean rfoe;
synchronized (lock) {
state = FINALIZERS;
rfoe = runFinalizersOnExit;
}
if (rfoe) runAllFinalizers();
}
它最终会调用runHooks方法,然后启动在上面静态块中添加的Runnable线程,最终启动所有已注册的钩子程序。
private static void runHooks() {
for (int i=0; i < MAX_SYSTEM_HOOKS; i++) {
try {
Runnable hook;
synchronized (lock) {
currentRunningHook = i;
hook = hooks[i];
}
//该run方法最终执行静态块中的runHooks()方法。
if (hook != null) hook.run();
} catch(Throwable t) {
if (t instanceof ThreadDeath) {
ThreadDeath td = (ThreadDeath)t;
throw td;
}
}
}
}
接下来找到Terminator
中:
class Terminator {
private static SignalHandler handler = null;
/* Invocations of setup and teardown are already synchronized
* on the shutdown lock, so no further synchronization is needed here
*/
static void setup() {
if (handler != null) return;
SignalHandler sh = new SignalHandler() {
public void handle(Signal sig) {
Shutdown.exit(sig.getNumber() + 0200);
}
};
handler = sh;
// When -Xrs is specified the user is responsible for
// ensuring that shutdown hooks are run by calling
// System.exit()
//这就是响应中断的方法
try {
Signal.handle(new Signal("INT"), sh);
} catch (IllegalArgumentException e) {
}
try {
//TERM对应15,即kill -9
Signal.handle(new Signal("TERM"), sh);
} catch (IllegalArgumentException e) {
}
}
其中Signal.handle()就是处理中断信号的方法,最终会通过sh回调Shutdown.exit()方法。最终触发sequence()方法被调用,然后调用所有注册的钩子程序。
五、最后
初步介绍了一下PreDestroy的原理和钩子程序的一些细节,由于标题只是讲PreDestroy,所以其中省略了不少spring的实现细节。谢谢大家~