I studied how to fix this problem, but cannot find a suitable solution.
Here's the problem:
I have a Java EE application where many users can log in, they are represented by a list of items, and they can select and edit any of them.
All users see the same list of items. As already mentioned, they can edit an element, but I would like to limit the editing function to one user. That is, many users can edit different elements at the same time, but only one user can edit a specific element.
When one user edits an item, a message should appear to any other user trying to edit that item.
I implemented this by setting the flag in the element, inUse, to true, and then checked it. When the user edits the item, either by clicking Save or Cancel, the flag is set to false. The problem with this approach is to consider when the user leaves his browser open or the browser is closed.
I tried to set the session timeout, but I can not get this to work, because when the session time ends, I do not have access to this element. I only have access to the httprequest session id.
Perhaps this is the wrong approach, as it seems that these are problems that many applications may have, and there is a smaller hacky solution.
I studied the use of threads and synchronized methods, but I donβt know how this will work, because as soon as the user enters the edit control screen, the method terminates and releases the lock.
I found this solution. Only one user allowed to edit content at a time , but not sure if this is the way to Java.
Is there a more elegant / java solution? If so, can you point me in the right direction, please? How do you implement this?
Thanks!
Solution: Although initially I thought that optimistic locking is the way to go, I quickly realized that this would not work for my environment. I decided to go with a combination of pessimistic blocking ( http://www.agiledata.org/essays/concurrencyControl.html#PessimisticLocking ) and timeouts.
When accessing an element, I set the inUse field to true and the field of the last access of the object to the current time.
Every time someone tries to edit an object, I check the inUse field and lastAccessed field + 5 minutes. So basically I give 5 minutes to edit the user.