如果在另一个线程中执行,Hibernate 不会 return 连接

Hibernate does not return connection if exectuted in another thread

我遇到了问题,我需要 运行 并行处理多项任务。
为此,我正在使用 Futures。
其中一项任务是通过休眠在 postgres 数据库上执行一个简单的 select,问题是每次执行此任务时都会创建一个新的 postgres 连接,很快 postgres 将不再接受任何连接。
应用程序 运行 在 tomcat 服务器上并使用连接池。
如果我不在不同的线程中执行任务,它工作正常。

这是使用hibernate的方法:

@Override
public Future<MonitoringResult> performMonitoringAction()  {

    return getExecutorService().submit(() -> {
        long milliseconds = System.currentTimeMillis();

        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtil.getCurrentInstance().newSession();
            tx = session.beginTransaction();
            List<Entity> sle = (List<Entity>) session.createQuery("from Entity").list();

            return new MonitoringResult(System.currentTimeMillis() - milliseconds, true);
        } catch (Exception e) {
            return new ExceptionMonitoringResult(System.currentTimeMillis() - milliseconds, e);
        } finally {
            if (tx != null) {
                tx.commit();
        }
            if (session != null) {
                session.close();
            }
        }
    });
}

它是这样叫的:

public Response all() {

    List<Future<MonitoringResult>> runningMonitorTasks = new ArrayList<>(monitoredServices.length);

    // start all monitoring services
    for (MonitorableService monitoredService : monitoredServices) {
        runningMonitorTasks.add(monitoredService.performMonitoringAction());
    }

    HashMap<String, MonitoringResult> resultMap = new HashMap();

    // collect results of monitoring services
    for (int i = 0; i < monitoredServices.length; i++) {
        MonitorableService monitoredService = monitoredServices[i];
        Future<MonitoringResult> runningTask = runningMonitorTasks.get(i);

        MonitoringResult result;
        try {
            result = runningTask.get(60, TimeUnit.SECONDS); // wait till task is finished
        } catch (TimeoutException | InterruptedException | ExecutionException ex) {
            LOGGER.log(Level.SEVERE, "Monitoring task failed", ex);
            result = new ExceptionMonitoringResult(-1, ex);
        }

        logIfUnreachable(result, monitoredService);
        resultMap.put(monitoredService.getServiceName(), result);
    }

    return Response.ok(resultMap).build();
}

这样调用效果很好:

public Response all() {

    HashMap<String, MonitoringResult> resultMap = new HashMap();

    // execute monitoring services
    for (MonitorableService monitoredService : monitoredServices) {
        Future<MonitoringResult> result = monitoredService.performMonitoringAction();
        MonitoringResult get;
        try {
            get = result.get();
            logIfUnreachable(get, monitoredService);

        } catch (InterruptedException | ExecutionException ex) {
            Logger.getLogger(RestMonitorService.class.getName()).log(Level.SEVERE, null, ex);
            get = new ExceptionMonitoringResult(-1, ex);
        }
        resultMap.put(monitoredService.getServiceName(), get);

    }

    return Response.ok(resultMap).build();
}

HibernateUtil class:

public class HibernateUtil implements ServletContextListener {

    private static HibernateUtil currentInstance;
    private SessionFactory sessionFactory;
    private ServletContext servletContext;

    private final Log logger = LogFactory.getLog(LoginInfo.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // set current instance
        currentInstance = this;

        Configuration cfg = new Configuration().configure();
        StandardServiceRegistryBuilder builder = new    StandardServiceRegistryBuilder().applySettings(
                cfg.getProperties());
        sessionFactory = cfg.buildSessionFactory(builder.build());

        servletContext = sce.getServletContext();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // close session factory
        if(sessionFactory!=null){
            sessionFactory.close();
        }
        sessionFactory = null;

    }

    public static HibernateUtil getCurrentInstance() {
        return currentInstance;
    }

    public Session newSession() {
        return sessionFactory.openSession();
    }
}

还不能发表评论,可能值得检查 HibernateUtil.getCurrentInstance() 的来源,看看它在做什么,它可能使用一些本地线程或创建一个新的连接池。通常当连接耗尽时,可能是由于创建了一个新池而不是使用现有池来获取连接。

答案是真实的答案是问题发生在与我预期不同的地方。但我也会分享我的解决方案。

另一项服务(不是我提出的问题)使用了休眠功能。 我在 Web 应用程序的正常调用中有一个侦听器在关闭连接之前和之后打开连接。 但是因为服务现在在不同的线程上执行,连接被打开但从未关闭,因为监听器没有被调用。