使用 EJB 3.0,两个线程将尝试运行此代码(即在无状态会话 bean 中)。两个线程都能够通过 if 语句并打印出该语句。
userTransaction.begin(); //userTransaction is of class UserTransaction
myEntity = entityManager.find(MyEntity.class, id); //entityManager is of class EntityManager
if (myEntity.getStatus() != "DONE") {
myEntity.setStatus("DONE");
entityManager.merge(myEntity);
System.out.println("Only one thread should be running this");
}
userTransaction.commit();
我尝试将事务隔离级别设置为可序列化但没有成功:
org.hibernate.Session session = (org.hibernate.Session) entityManager.getDelegate();
session.connection().setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
也许我使用了错误的方法。
更新
不能使用 Singleton 会话 bean,因为 Jboss 5 不支持它们。现在我正在尝试以下代码来解决我在其他时候遇到死锁的问题:
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
connection.setAutoCommit(false);
//selectStatement and updateStatement are of type PreparedStatement
selectStatement = connection.prepareStatement("SELECT STATUS FROM MYTABLE WHERE STATUS != 'DONE' AND ID=?");
selectStatement.setInt(1, id);
updateStatement = connection.prepareStatement("UPDATE MYTABLE SET STATUS = 'DONE' WHERE ID=?");
updateStatement.setInt(1, id);
resultSet = selectStatement.executeQuery();
if (resultSet.next()) {
updateStatement.executeUpdate();
}
connection.commit();