Reputation: 4040
Hi,
We have an application (J2EE/Hibernate/JPA) with several users making actions on a common entity.
To simplify, let's say this application is like Google docs : A shared document on which many users can update at the same time.
We have chosen optmistic lock to handle concurrency :
So far, so good.
But now, we have added background processes (quite fast ones) to this application. They regularly make changes (let say it replace any occurence of a word by another).
It is ok for those job to fail. Their task is not urgent, and they can try the same task the next time (10 seconds after).
The problem with the optimistic lock in that situation is that now a single user cannot perform anymore long actions on te whole document.
Indeed, if a user changes the font of the whole document (on all sentences), and this action takes a while (> 10 sec), then in the meantime the background process will change some words, and the longer action (= the user action : change font) will fail on concurrent access.
This is not acceptable to show this mesage to the user : "Your action failed because some technical process was running at same time".
And since the background process could retry later, we would rather have it fail.
How do we setup pessimistic lock for some actions / actors , within a optimistic lock approach ?
In order to keep the optimistic approch for the users, we have thought of the following solution :
This way, the processes will only be able to run at idle time, while the user is not doing anything.
Is this a good approach ? We could not find any article / discussion about good practices for hybrid types of locks.
Upvotes: 3
Views: 239
Reputation: 15758
For the "document" it is the typical case of read-write lockings.
A read-write lock works so, that multiple readers can lock the resource parallelly, but only one writer. Because of this, readers and writers are mutually exclusive.
Your real users would put a "read" lock to the document, when they start to edit. More than one of them can enter at the same time, each of them will edit a different sentence.
Your background process is the writer in this case, it can enter (by putting a "write" lock) if no readers (and no other writers) are locking this document. Then the background process can do its changes.
Also, it may happen that a user fails to open the document, but - since the background process is fast - it is very unlikely (and it's temporal, you can retry 1 sec later, even without notifying the user).
To provide you some reference, here's how you can use LockModeType.READ
and LockModeType.WRITE
in JPA: Read-Write lockings in JPA
Upvotes: 1