2

我正在使用 spring 事务模板在线程中执行多个事务,根据 spring 事务模板它是线程安全的,但是它不会长时间释放连接。我正在使用由 tomcat jndi 上下文配置的 c3p0 连接池。

这是代码片段:

for (SearchProcessorType[] processorTypes : getProcessorChainTypes()) {
        if (processorTypes.length > 1) {
        ExecutorService doerService = Executors.newFixedThreadPool(processorTypes.length);

        for (final SearchProcessorType processorType : processorTypes) {
            if(searchData.getException() != null) {
                if(searchData.getException() instanceof SearchException) {
                    throw (SearchException)searchData.getException(); 
                }
                throw new RuntimeException(searchData.getException().getMessage());
            }
            doerService.submit(new Runnable() {

                @Override
                public void run() {

                    try {

                        if (!searchData.isSkipType(processorType)) {
                            final SearchProcessor processsor = SearchProcessor.get(processorType);
                            if (authentication != null) {
                                SecurityContextHolder.getContext().setAuthentication(authentication);
                            }
                            if (processsor.isTransactional()) {
                                transactionTemplate.execute(new TransactionCallbackWithoutResult() {

                                    @Override
                                    protected void doInTransactionWithoutResult(TransactionStatus status) {
                                        processsor.process(searchData, (SearchResponse<Object>) response);

                                    }
                                });
                            } else {
                                processsor.process(searchData, (SearchResponse<Object>) response);
                            }
                        }
                    } catch (Exception ex) {
                        searchData.setException(ex);
                    }
                }
            });
        }
        doerService.shutdown();
        while (!doerService.isTerminated()) {
            // Wait for processors to get completed
        }
        if(searchData.getException() != null) {
            if (searchData.getException() instanceof SearchException) {
                throw (SearchException) searchData.getException();
            } else {
                throw new RuntimeException(searchData.getException());
            }
        }
    } else if (!searchData.isSkipType(processorTypes[0])) {
        SearchProcessor.get(processorTypes[0]).process(searchData, (SearchResponse<Object>) response);
    }
}
4

0 回答 0