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

时间:2020-11-03 07:34:15

标签: java multithreading hibernate connection-pooling

我有一个问题,我需要并行运行多个任务。
为此,我正在使用期货。
其中一项任务是通过休眠在postgres数据库上进行简单选择,问题是每次执行此任务都会创建一个新的postgres连接,不久后postgres将不再接受任何连接。
该应用程序在tomcat服务器上运行,并使用连接池。
如果我不在其他线程中执行任务,则效果很好。

这是使用休眠模式的方法:

@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类:

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();
    }
}

2 个答案:

答案 0 :(得分:1)

尚无法发表评论,可能值得检查HibernateUtil.getCurrentInstance()的源以查看其作用,它可能使用一些threadlocal或创建新的连接池。通常在连接耗尽时,可能是由于创建新池而不是使用现有池来获得连接。

答案 1 :(得分:0)

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

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

相关问题