Javaとデータベースの2つの方法でロックを追加


Javaロック方式で同期
publicstatic synchronized int generate(StringtableName){
Stringsql = "select value from t_table_id where table_name=?";
Connectionconn = null;
PreparedStatementpstmt = null;
ResultSetrs = null;
intvalue = 0;
try{
conn= DbUtil.getConnection();
pstmt= conn.prepareStatement(sql);
pstmt.setString(1,tableName);
rs= pstmt.executeQuery();
rs.next();
//                        if(!rs.next()){
//                                thrownew RuntimeException();
//                        }
value= rs.getInt("value");
value++;
modifyValueField(conn,tableName,value);
}catch(Exceptione){
e.printStackTrace();
thrownew RuntimeException();
}finally{
DbUtil.close(rs);
DbUtil.close(pstmt);
DbUtil.close(conn);
}
returnvalue;
}

データベースによるロック:
	          
	 sql     for update     ,          ,          。            。
	public static int generate(String tableName){
			//         for update
			String sql = "select value from t_table_id where table_name=? for update";
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			int value = 0;
			try{
				conn = DbUtil.getConnection();
				//       false
				DbUtil.beginTransaction(conn);
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, tableName);
				rs = pstmt.executeQuery();
				rs.next();
	//			if(!rs.next()){
	//				throw new RuntimeException();
	//			}
				value = rs.getInt("value");
				value++;
				modifyValueField(conn,tableName,value);
				//    
				DbUtil.commitTransaction(conn);
			}catch(Exception e){
				e.printStackTrace();
				//    
				DbUtil.rollbackTranscation(conn);
				throw new RuntimeException();
			}finally{
				DbUtil.close(rs);
				DbUtil.close(pstmt);
				DbUtil.resetConnection(conn);
				DbUtil.close(conn);
			}
			return value;
		}