LoginSignup
16
17

More than 5 years have passed since last update.

アプリにおける排他制御 -楽観的/悲観的ロックの違いと使い所-

Last updated at Posted at 2018-06-29

対象読者

-「楽観的」とか「排他的」とか聞いたことあるけどよくわかっていない方

楽観的ロックと悲観的ロック

楽観的ロック

更新対象のデータが、データの取得時点から更新されていないことを確認したうえで更新することでデータの整合性を保証する

悲観的ロック

更新対象のデータを取得時点から明示的にロックしてから更新する(=他トランザクションによる更新を防ぐ)ことでデータの整合性を保証する

表で見る楽観的ロック・悲観的ロック

楽観的ロック 悲観的ロック
排他制御の主体 アプリケーション データベース
(DBMS)
実現手段 ・データ取得時の最終更新日時またはバージョン番号を条件に含めて更新する*1 ・「SELECT FOR UPDATE」によってデータを取得して更新する
使いどころ ・更新頻度が高くない
・同時更新されることがあまりない
・トランザクションが短い
・更新頻度が高い
・同時更新されることが多い
アプリ方式としての採用状況
※私見
よく使われる*2 あまり使われない

*1 最終更新日時の場合、同一時点に更新処理が実行された場合の一意性を保証できないため、基本的にはバージョン用カラム(更新の度に+1することで更新状態を把握するためのカラム)を使用することをおすすめします

*2 以下が参考になりました

So which one should you pick?

The answer is that, there is no correct answer – it depends. You should pick your locking scheme based on your application requirements.

Unless you expect a document to be heavily contended, optimistic locking is going to be much lower overhead than pessimistic locking – grab the item you need, update it quickly and attemp to apply it. If some other actor in the system beat you to it, you can just retry till you succeed.

Optimistic or pessimistic locking – Which one should you pick?

最後に

今後追記します。たぶん。

参考

データの同時更新を防ぐための排他制御

16
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
17