最近在使用线程池做spring的任务Test时,启动服务抛出异常:Singleton bean creation not allowed while the singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
具体的错误信息如下:
javaException in thread "pool-3-thread-1" Exception in thread "pool-3-thread-2" org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'jade.datasourceFactory': Singleton bean creation not allowed while the singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:216)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:534)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:523)
at net.paoding.rose.jade.context.spring.SpringDataSourceFactoryDelegate.getDataSource(SpringDataSourceFactoryDelegate.java:38)
at net.paoding.rose.jade.dataaccess.DefaultDataAccessFactory.getDataAccess(DefaultDataAccessFactory.java:46)
at net.paoding.rose.jade.statement.SelectQuerier.execute(SelectQuerier.java:60)
at net.paoding.rose.jade.statement.SelectQuerier.execute(SelectQuerier.java:56)
at net.paoding.rose.jade.statement.JdbcStatement.execute(JdbcStatement.java:112)
at net.paoding.rose.jade.context.JadeInvocationHandler.invoke(JadeInvocationHandler.java:143)
at com.sun.proxy.$Proxy53.getSapPayDetailList(Unknown Source)
at com.xiaomi.mifi.scf.accountcenter.service.gateway.SapPayDetailService.getSapPayDetailList(SapPayDetailService.java:45)
at com.xiaomi.mifi.scf.accountcenter.task.reconcile.SapReconcile.sapPaydetailClean(SapReconcile.java:70)
at com.xiaomi.mifi.scf.accountcenter.task.reconcile.SapReconcile.lambda$reconcile$0(SapReconcile.java:58)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
经过原因分析,是单例的bean在创建的时候,容器已经处于销毁阶段,生命周期不同,不允许再次创建生产Bean。为什么会发生这个问题呢?
具体看了代码,是因为我的任务提交给了线程池,test主线程运行时,启动了线程池,线程池中的任务会加载bean,但因为异步原因,任务提交给线程池后,主线程结束了,开始销毁bean容器,而线程池任务有需要创建出bean,所以出现上述的异常情况。
3.1 测试用例中增加线程池的任务判断,如果有线程池任务未完成,当前主线程阻塞。
java@Test
public void test2(){
sapReconcile.reconcile("123",2);
while (sapReconcile.executor.getActiveCount() > 0){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3.2 利用屏障等同步工具,等待线程执行完成后再退出主线程。
本文作者:xiech
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!