Sobes.tech
Senior

What happens if you do not add a pessimistic lock? What locking options are available?

sobes.tech AI

Answer from AI

If pessimistic locking is not used in scenarios where data changes may occur concurrently, issues with data integrity can arise, such as lost updates or reading inconsistent data. Pessimistic locking prevents simultaneous access to a resource by locking it for other transactions until the current one is finished.

Locking options:

  • Pessimistic Locking: locks data immediately upon reading or updating to prevent other transactions from modifying it.
  • Optimistic Locking: does not lock data upon reading but checks upon saving whether the data has changed since it was read (for example, using a version or timestamp).
  • Row-level Locking: locking at the row level of a table.
  • Table-level Locking: locking the entire table.

Example of optimistic locking in JPA:

@Entity
public class Employee {
    @Version
    private Long version;
    // other fields
}

When saving, JPA will check the version and throw an exception if the data has been modified by another process.