【问题标题】:Multithread issues in using Hibernate SessionFactory使用 Hibernate SessionFactory 的多线程问题
【发布时间】:2011-06-25 23:32:52
【问题描述】:

有一张桌子'temp' .. 代码:

CREATE TABLE `temp` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `student_id` bigint(20) unsigned NOT NULL,
  `current` tinyint(1) NOT NULL DEFAULT '1',
  `closed_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_index` (`student_id`,`current`,`closed_at`),
  KEY `studentIndex` (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

对应的 Java pojo 是 http://pastebin.com/JHZwubWd 。此表具有唯一约束,因此每个学生只能有一条记录处于活动状态。

2)我有一个测试代码,它确实尝试不断为学生添加记录(每次将旧的活动记录设为非活动记录并添加新的活动记录),并且在不同的线程中访问一些随机(不相关) 桌子。 代码:

public static void main(String[] args) throws Exception {
        final SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        int runs = 0;
        while(true) {
            Temp testPojo = new Temp();
            testPojo.setStudentId(1L);
            testPojo.setCurrent(true);
            testPojo.setClosedAt(new Date(0));
            add(testPojo, sessionFactory);
            Thread.sleep(1500);

            executorService.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    Session session = sessionFactory.openSession();
                    // Some dummy code to print number of users in the system.
                    // Idea is to "touch" the DB/session in this background
                    // thread.
                    System.out.println("No of users: " + session.createCriteria(User.class).list().size());
                    session.close();
                    return null;
                }
            });
            if(runs++ > 100) {
                break;
            }
        }

        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.MINUTES);
    }

private static void add(final Temp testPojo, final SessionFactory sessionFactory) throws Exception {
        Session dbSession = null;
        Transaction transaction = null;
        try {
            dbSession = sessionFactory.openSession();
            transaction = dbSession.beginTransaction();

            // Set all previous state of the student as not current.
            List<Temp> oldActivePojos = (List<Temp>) dbSession.createCriteria(Temp.class)
                    .add(Restrictions.eq("studentId", testPojo.getStudentId())).add(Restrictions.eq("current", true))
                    .list();
            for(final Temp oldActivePojo : oldActivePojos) {
                oldActivePojo.setCurrent(false);
                oldActivePojo.setClosedAt(new Date());

                dbSession.update(oldActivePojo);
                LOG.debug(String.format("  Updated old state as inactive:%s", oldActivePojo));
            }
            if(!oldActivePojos.isEmpty()) {
                dbSession.flush();
            }

            LOG.debug(String.format("  saving state:%s", testPojo));
            dbSession.save(testPojo);
            LOG.debug(String.format("  new state saved:%s", testPojo));

            transaction.commit();

        }catch(Exception exception) {
            LOG.fatal(String.format("Exception in adding state: %s", testPojo), exception);
            transaction.rollback();
        }finally {
            dbSession.close();
        }
    }

运行代码后,经过几次运行,我得到一个索引约束异常。发生这种情况是因为出于某种奇怪的原因,它没有找到最新的活动记录,而是找到了一些较旧的陈旧活动记录,并在保存之前尝试将其标记为非活动记录(尽管数据库实际上已经存在新的活动记录)。

请注意,这两个代码共享同一个 sessionfactory,并且两个代码都在完全不同的表上工作。我的猜测是某些内部缓存状态变脏了。如果我为前台和后台线程使用 2 个不同的 sessionfactory,它工作正常。

另一个奇怪的事情是,在后台线程(我打印用户数的地方),如果我将它包装在一个事务中(即使它只是一个读取操作),代码就可以正常工作! Sp 看起来我需要将所有数据库操作(无论读/写)包装在一个事务中,以便它在多线程环境中工作。

有人能指出问题吗?

【问题讨论】:

  • 你能澄清违反了哪个约束吗?完整的堆栈跟踪也可能会有所帮助。

标签: multithreading hibernate sessionfactory


【解决方案1】:

是的,基本上,事务划分总是需要的:

Hibernate documentation 说:

数据库或系统事务边界始终是必需的。在数据库事务之外不能与数据库进行通信(这似乎使许多习惯于自动提交模式的开发人员感到困惑)。始终使用明确的事务边界,即使对于只读操作也是如此。根据您的隔离级别和数据库功能,这可能不是必需的,但如果您始终明确划分事务,则没有缺点。

在尝试重现您的设置时,我遇到了一些由于缺乏事务分界而导致的问题(尽管与您的不同)。进一步调查显示,有时,根据连接池配置,add() 与之前的call() 在同一数据库事务中执行。将beginTransaction()/commit() 添加到call() 解决了这个问题。这种行为可能会导致您的问题,因为根据事务隔离级别,add() 可以使用在事务开始时(即在之前的call() 期间)拍摄的数据库的陈旧快照。

【讨论】:

    猜你喜欢
    • 2013-08-16
    • 2011-11-13
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2016-02-23
    相关资源
    最近更新 更多