碰巧在讨论 悲观乐观并发问题,看了不少国内的博客讲的太细,举了太多的例子,把人给绕的晕乎乎的,这里直接来个清晰干脆的英文版,后面我就献丑来几句中午的:
I remember that this was a tricky thing for me to understand and remember when I first got started with databases, so I thought I might help someone out by explaining these in a simple way.
Optimistic and pessimistic locking (or concurrency control) are ways of addressing a problem such as the following:
User A reads the row for customer #123
User B reads the row for customer #123
User B updates the row for customer #123
User A updates the row for customer #123 and overwrites User B's changes
The problem here is that one user has changes that conflict with another user's, and unless we do something about it, we'll lose User B's changes without even noticing.
The pessimistic concurrency control approach is to have the database server lock the row on User A's behalf, so User B has to wait until User A has finished its work before proceeded. We effectively solve the problem by not allowing two users to work on the same piece of data at the same time. It just prevents the conflict.
The optimistic concurrency control approach doesn't actually lock anything - instead, it asks User A to remember what the row looked like when he first saw it, and when it's time to update it, the user asks the database to go ahead only if the row still looks like he remembers it. It doesn't prevent a possible conflict, but it can detect it before any damage is done and fail safely.
You can remember which is which by picturing it this way:
The pessimistic approach is a user thinking "I'm sure someone will try to update this row at the same time as I will, so I better ask the database server to not let anyone touch it until I'm done with it."
The optimistic approach is a user thinking "I'm sure it's all good and there will be no conflicts, so I'm just going to remember this row to double-check later, but I'll let the database server do whatever it wants with the row."
There are other differences in how errors are handled, how smart the clients need to be, what the performance is on client and server for each approach, etc., but hopefully this clearly explains what each approach is all about.
Enjoy!
两者的分水岭在于:
1. 悲观式并发处理方式,适用于并发性大的情况,我知道有好多人会跟我抢着改同一条数据,所以我要加排他锁,当我拿到数据并修改的时候,不允许任何人碰它(也不允许读它)。
2. 乐观式并发处理方式,适用于并发性特别小的情况,很少有人跟我抢着改同一条数据,但也不排除并发的可能性。虽然在去修改那条数据的时候,我不会加锁独占那条数据,但是我会心里有数那个数据改之前应该长什么样。补充,只要当数据跟我所断定的一个模样的时候,我才会去修改它;而一旦数据跟我断定的不一样,那说明有人提前我给它动手脚了,我就不应该继续修改它,而返回相应的错误或者信息给Requestor,让它来决策再怎么做。
外加自己的总结下:悲观式处理,会因并发的数量级大而导致响应缓慢,因为都在互相等锁。 而乐观式处理都会瞬间得到结果,相对来说performance高,注意,是相对,因为失败的那些请求者有可能继续额外的一轮请求,间接的导致performance负荷增大,这就要看 乐观式的具体处理方法了。
转发请注明出处:http://hi.baidu.com/songeastchang/item/c923fd9975465fbecc80e503