如何處理 Web 應用邏輯和數據庫並發? (How to handle Web application logic and database concurrency?)


問題描述

如何處理 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.

(by Teddyforty‑two)

參考文件

  1. How to handle Web application logic and database concurrency? (CC BY‑SA 2.5/3.0/4.0)

#race-condition #database-concurrency #Web #concurrency






相關問題

Javascript 和 DOM 事件交互和可能的競爭條件 (Javascript and DOM event interaction and possible race conditions)

防禦 System.Collections.Concurrent.ConcurrentDictionary 中的競爭條件 (Defending against race conditions in System.Collections.Concurrent.ConcurrentDictionary)

可能一次在 PHP 中多次寫入同一個文件? (Potentially write to same file in PHP multiple times at once?)

靜態線程安全 (Thread safety of static)

CancellationTokenSource.Cancel 引發 ObjectDisposedException (CancellationTokenSource.Cancel throws an ObjectDisposedException)

如何處理 Web 應用邏輯和數據庫並發? (How to handle Web application logic and database concurrency?)

Linux IRQ 處理程序中的固有競爭條件 (Inherent race condition in Linux IRQ handlers)

SQL Server 進程隊列競爭條件 (SQL Server Process Queue Race Condition)

WCF 服務僅在客戶端收到結果時才寫入日誌 (WCF service writes log only if client receives results)

將 SWT 與 JOGL 一起使用時發生隨機崩潰(競爭條件?) (Random crashes when using SWT with JOGL (race condition?))

std::shared_ptr 的線程安全 (Thread safety with std::shared_ptr)

如何更新 JSON 類型列中的特定值 (How can I update specific value from my JSON type column)







留言討論