Skip to content

Instantly share code, notes, and snippets.

@magicliang
Created January 8, 2020 10:40
Show Gist options
  • Save magicliang/4052717189f321bf868731b5cf3bb4e6 to your computer and use it in GitHub Desktop.
Save magicliang/4052717189f321bf868731b5cf3bb4e6 to your computer and use it in GitHub Desktop.
依赖于 spring 钩子
/**
* 在一个 bean 被销毁以前对它应用本处理器
* Apply this BeanPostProcessor to the given bean instance before its
* destruction, e.g. invoking custom destruction callbacks.
* <p>Like DisposableBean's {@code destroy} and a custom destroy method, this
* callback will only apply to beans which the container fully manages the
* lifecycle for. This is usually the case for singletons and scoped beans.
*
* @param bean the bean instance to be destroyed
* @param beanName the name of the bean
* @throws BeansException in case of errors
* @see DisposableBean#destroy()
* @see AbstractBeanDefinition#setDestroyMethodName(String)
*/
@Override
public void postProcessBeforeDestruction(final Object bean, final String beanName) throws BeansException {
// 先清理 bean 和 线程池的映射表的 entry
ExecutorElement executorElement = this.beanToPool.remove(bean);
// 如果依赖 requiresDestruction,这里不会返回 null,但为预防万一,还是做判空检查。
if (null != executorElement) {
// 获取全局引用数据
AtomicInteger referenceCount = this.poolReference.get(executorElement);
// 如果当前对线程池的应用已经为空或者引用数在本次清理中降为 0,则直接关闭线程池,且清理 poolReference。
if (null == referenceCount || 0 == referenceCount.decrementAndGet()) {
ExecutorServiceUtils.shutdownExecutor(executorElement.getExecutorService());
poolReference.remove(executorElement);
}
}
}
/**
* 确认一个 bean 被销毁之前要不要被这个处理器处理。
* 默认都会被这个处理器处理。
*
* @param bean the bean instance to check
* @return {@code true} if {@link #postProcessBeforeDestruction} is supposed to
* be called for this bean instance eventually, or {@code false} if not needed
* @since 4.3
*/
@Override
public boolean requiresDestruction(final Object bean) {
return beanToPool.containsKey(bean);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment