How to reserve/lock a record/object for update

This tip describes a simple method to handle reserving a database record or an object while a user updates it.

The goal of an update reservation is to prevent two users from updating the same information at the same time. If this is allowed, the first user will typically lose their updates. At the same time, a user must not be allowed to lock a record for two hours while they attend a meeting.

My solution is to create a date/time field in the database record or object. In Java, this is more easily represented as a "long", as arithmetic is easier. Here are the rules:

1. If System.currentTimeMillis - lockTime <= maxLockMillis, a current lock exists and a new user cannot lock the record.

2. If System.currentTimeMillis - lockTime <= maxLockMillis, an expired lock exists, and a new user may "steal" the lock by updating lockTime with the current millis.

3. If a user gained a lock, the lock must still exist before the record/object is updated. Note that an expired lock is still valid, regardless of how old it is. However, if another user "stole" the lock, no update is allowed.

4. During the update, the lockTime is reset to 0.

maxLockMillis can be set to any value, and it can vary between tables/objects.