問題描述
如何處理 Web 應用邏輯和數據庫並發? (How to handle Web application logic and database concurrency?)
假設我有一個名為 items
的表。我的 webapp 的用戶可以刪除 items
表的行,但我不想讓表為空。
所以目前我的應用程序中有這樣的代碼:
if (itemsCount() <= 1) {
don't delete;
}
else {
delete;
}
但我意識到這段代碼容易受到並發問題的影響。例如,如果當前items
的大小是2,並且有兩個線程幾乎同時執行這段代碼,那麼表可能會變空。
我認為這個問題對於編寫 webapps 的人來說是很常見的。人們應該已經解決了。有哪些可用的解決方案?
參考解法
方法 1:
The most common solution is to use a Transaction Manager. In your case, the Transaction Manager would coordinate the thread execution to make sure that only one thread at a time access and updates the table.
You didn't mention which language and which kind of environment you are using, but assuming Java and JEE, transaction management is quite easy. Start here.