optimistic lock vs pessimistic lock
- optimistic lock : 말 그대로 lock을하고 update 를 하는 것에 대해 낙관적이다. 일단, 각 table 별로 추가적인 column 을 사용한다. hash, timestamp, version 등이다. 실패하지 않을것이라고 생각하고, lock 없이 update 를 시도한다. 대신, 읽었을때와 쓰는 순간에 version 을 비교해서 같으면 그사이 변경이 없었다는 뜻이므로 update 를 마무리를 하고, version값을 1 증가시킨다. 만일 비교한 값이 다르면 그사이에 이미 update 가 되었기 때문에 현재의 transaction 결과물은 무의미해진다. 따라서 이 결과는 쓰일수가 없고, application level 에서 재시도를 할지, 무시할지 등에 대해 처리를 해야한다.
- pessimistic lock : update 를 하는것에 대해 비관적이다. 그러므로 update 를 하기 전 해당 row 에 대해 lock 을 걸어잠그고 update 를 한다. 그렇기 때문에 일단 lock 을 얻었으면 별다른 이유가 없는한 현재 transacton은 실패하지 않고 DB 에 쓰이게 된다. 다만, 그사이에 다른 transaction 에서 접근하는데 제약이 있다. 제약은 다시 두종류로 나누게 된다.
- shared / read lock : read 는 하게 해준다
- exclusive / write lock : read 도 못하게 한다
- 성능 측면에서 보면, pessmistic lock 이 무조건 걸어잠그고 들어가기 때문에 optimistic lock 이 더 유리하다고 볼 수는 있다. pessmistic lock 은 더구나 deadlock 의 잠재적인 위험성도 가지고 있다.
- concurrent access 에 따른 conflict 가 적을 것으로 예상되면, optimistic lock 을 써도 된다고 볼수 있겠다. 하지만 conflict 가 매우 많이 발생할 것 같은 시나리오라면, optimistic lock 을 쓰면 하나를 제외한 거의 모든 thread 가 ObjectOptimisticLockingFailureException 를 발생시킬 것이기 때문에, pessimistic lock으로 가는게 좋을것 같다.
- optimistic lock means that you make use of another column called "version" and every time you want to update the row, you need to compare the version before the update and about to update. If the version is as same, it means no other thread changed the row. so you can go. Otherwise, it means that the row is affected by other transactions. so this change should be aborted.
- pessimistic lock means you always lock the row when you start the transaction. there are two ways you can make choices in how you want to allow other threads. you can let others can read or block them from reading.
- pessimistic can cause deadlock since they lock the row. optimistic should use an extra column to compare it. When there is a big chance of conflict due to concurrency, it's better to use pessimistic because optimistic transactions will fail at the end, and the other way around regarding optimistic lock.
Comments
Post a Comment