你應該總是有一個約束,但是這個要求在某些情況下可能是有效的。
一個簡單而優雅的解決方案是做一個MERGE
或做一個SELECT
和INSERT
。所以,執行多少次,你是安全的。
通過將過程調用放入線程類的syncronized
方法中,可以實現客戶端實現。所以,它不能並行運行。
public void your_method() {
// Other statements
synchronized(this) { // blocks "this" from being executed by parallel threads
// call your oracle stored proc here
}
}
但是,如果跨不同平臺有多個客戶端,則可能必須在Oracle本身編寫一些東西! 一個簡單而優雅的解決方案是做一個MERGE
或做SELECT
和INSERT
procedure persist(id_1 out Number,
id_2 out Number)
is
retcode NUMBER := 0;
begin
retcode := 100;
/* Checking for semaphore, else wait ! */
WHILE(retcode = 100)
LOOP
retcode = check_semphore(); /* Returns 100 if present else 0 */
IF(retcode = 100) THEN
/* Semaphore present */
NULL;
ELSE
write_semaphore;
/* probably a entry in a table with commit,
have to use savepoints, else every other transactions would be comitted! */
MERGE INTO middle_table m
USING (SELECT id_1,id_2 FROM dual) new_Values
ON (new_Values.id_1 = m.id_1
AND new_Values.id_2 = m.id_2)
WHEN NOT MATCHED
THEN
INSERT INTO middle_table VALUES(id_1,id_2);
delete_semaphore;
/* delete tht entry */
EXIT;
END IF;
END LOOP;
end;
/