문제

I am a bit confused on the benefits of optimistic locking in JPA.

I conducted a test with two threads and a single row on a versioned entity table.
Here is what I have found:

T1: begin tran
T1: fetch single entity
T1: Update field in entity
T1: sleep
T2: begin tran
T2: fetch single entity
T2: Update field in entity
T2: commit trans
T1: wake up
T1: commit trans - throws OptimisticLockException (expected)

Second test. Note the addition of a select statement.

T1: begin tran
T1: fetch single entity
T1: Update field in entity
T1: run select query on table (this causes a DB transaction to begin)
T1: sleep
T2: begin tran
T2: fetch single entity (this blocks until DB transaction of thread T1 completes!)
T2: Update field in entity
T2: commit trans
T1: wake up
T1: commit trans - ok, no exception. The fetch/update/commit of T2 happened after T1 commit. 

I wasn't really expecting any blocking to occur when using optimistic locking, however my understanding is that a database transaction has to be in place here so that the correct data is returned from the select statement.
Since JPA only seems to enter database transactions when absolutely necessary, can anyone explain what the benefits of optimistic locking are?

도움이 되었습니까?

해결책

In your first example you are correct that JPA is hanging on to the updates until it absolutely has to flush them. In the second example it has to flush them so that the select is working on up-to-date data.

One advantage of optimistic locking is that the database doesn't have to lock any tables. This allows your database to scale better because more clients can issue statements against it. The disadvantage is that it moves much of that concurrency control into the application layer.

This means that you will be required to implement the error handling or retry logic. In the case where you expect no contentious updates this can be good. In the case where you expect many clients to be updating the same JPA entities at the same time it can require a fair amount of application logic to handle the errors and intelligently retry the update without resorting to a "last-write-wins" situation.

You may find this blog post interesting https://blogs.oracle.com/carolmcdonald/entry/jpa_2_0_concurrency_and

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top