公司用的是spring mvc,我准备用多线程并发向数据库更新数据,大约启动了5个线程,遇到了如下错误,请高手帮忙!!!
(数据源和事务均由spring容器管理)
rg.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: Data source is closed
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:240)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:335)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at com.palm360.airport.service.impl.AdminMerchantFavoriteLogAnalysisServiceImpl$$EnhancerByCGLIB$$2d13ab30.insert(<generated>)
at com.palm360.airport.service.impl.AnalysisManagerServiceImpl$WorkThread.run(AnalysisManagerServiceImpl.java:141)
Caused by: java.sql.SQLException: Data source is closed
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1362)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource.getConnection(AbstractRoutingDataSource.java:148)
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:202)
... 9 more
------解决方案--------------------
猜测主线程已经停止了application context,关闭了数据源。同时,分线程还在执行数据库操作。就这样报错了。
还是看看你的代码架构吧。是用的单元测试?
------解决方案--------------------
想办法让线程运行完再结束测试主线程呗。
所有线程弄个列表,然后 thread.join();
------解决方案--------------------
是不是你在程序中 手动关闭了连接对象 一般spring容器不会关闭连接对象的。
------解决方案--------------------
List<Thread> threads;
for (Thread thread : threads) {
thread.join();
}
怎么不能并发,线程不还是跑着吗,只是要保证线程没结束的时候不能让application context结束
------解决方案--------------------
应该是并发处理数据那块有问题,
比如一个线程在获取到connection链接,其他线程正在关闭这个连接,然后这个线程执行了sql,结果发现已经关闭了,当然报错了。
不知道你dao怎么处理的。查一下你代码connection那块怎么写的