Oracle Select for update不工作,有时在一段时间后挂起



我正在用java做Oracle Select for Update,它有时会工作,有时它会挂起会话,无法删除锁定的会话(必须手动杀死会话)这适用于大多数情况下,但当我部署在两个服务器(web服务),并请求他们同时发生这种情况,我无法理解这是否是我的代码问题,我的代码

 public boolean checkJobStatus(long taskId)
{
    Connection con = null;
    PreparedStatement selectForUpdate = null;
    String lastJobStatus = null;
    boolean runNow = false;
    try
    {
        con = conPool.getConnection();
        con.setAutoCommit(false);
        selectForUpdate  = con.prepareStatement("SELECT LAST_JOB_STATUS FROM ADM_JOB WHERE TASK_ID = ? FOR UPDATE ");
        selectForUpdate.setLong(1, taskId);
        ResultSet resultSet = selectForUpdate.executeQuery();
        while(resultSet.next())
        {
            if (resultSet.getObject("LAST_JOB_STATUS") == null)
            {
                lastJobStatus = ScheduledJob.STATUS_FAILED;
            }
            else
            {
                lastJobStatus = resultSet.getString("LAST_JOB_STATUS");
            }
        }
     if(ScheduledJob.STATUS_RUNNING.equalsIgnoreCase(lastJobStatus) || ScheduledJob.STATUS_STARTED.equalsIgnoreCase(lastJobStatus))
     {
         runNow = false;
         // commit n update setting autocommit to true
         selectForUpdate = con.prepareStatement("UPDATE ADM_JOB SET LAST_JOB_STATUS =? WHERE TASK_ID = ?");
         selectForUpdate.setString(1, lastJobStatus);
         selectForUpdate.setLong(2, taskId);
         selectForUpdate.executeUpdate();
     }
     else
     {
         runNow =true;
         // commit n update setting autocommit to true
         selectForUpdate  = con.prepareStatement("UPDATE ADM_JOB SET LAST_JOB_STATUS =? WHERE TASK_ID = ?");
         selectForUpdate.setString(1, ScheduledJob.STATUS_STARTED);
         selectForUpdate.setLong(2, taskId);
         selectForUpdate.executeUpdate();
         con.commit();
         con.setAutoCommit(true);
     }
    } catch (SQLException e)
    {
        Logger.getLogger( "" ).log(Level.SEVERE, "Error in getting database connection", e);
        try
        {
            con.rollback();   // rolling back the row lock in case of a exception
        } catch (SQLException e1)
        {
            e1.printStackTrace();
        }
    }
    finally
    {
        DBUtility.close( selectForUpdate  );
        DBUtility.close( con );
    }

    return runNow;
}

Commit只发生在else分支中。如果这个条件没有发生,事务不会关闭,所以第二个线程永远挂起select for update。

最新更新