Sobes.tech
Junior — Middle

How can an optimistic locking mechanism be implemented?

sobes.tech AI

Answer from AI

An optimistic approach to data locking assumes that conflicts during concurrent data access will be minimal, so locks are not set in advance. Instead, when saving changes, it is checked whether the data has been modified since it was read.

In C#, this is often implemented using a version field (for example, an integer counter or timestamp) in the entity. When data is read, the version is stored, and during update, it is checked whether the current version matches the stored one. If the versions do not match, it means the data has been modified by another process, and the operation is rolled back or retried.

Example:

class Entity
{
    public int Id { get; set; }
    public string Data { get; set; }
    public int Version { get; set; } // version field
}

bool TryUpdate(Entity entity, string newData, int originalVersion)
{
    // Check if the version has not changed
    if (entity.Version != originalVersion)
        return false; // conflict

    entity.Data = newData;
    entity.Version++; // increment version
    return true;
}

In ORM, such as Entity Framework, there is built-in support for optimistic locking via the [Timestamp] attribute or version field configuration.